示例 1:截断字符串
// program to trim a string
const string = ' Hello World ';
const result = string.trim();
console.log(result);
输出
Hello World
在上面的示例中,使用 trim()
方法来截断字符串。
trim()
方法会删除字符串两端的空格。
示例 2:使用正则表达式截断字符串
// program to trim a string
function trimString(x) {
let trimValue = x.replace(/^\s+|\s+$/g,'');
return trimValue;
}
const result = trimString(' Hello world ');
console.log(result);
输出
Hello World
在上面的程序中,使用正则表达式和 replace() 方法来截断字符串。
/^\s+|\s+$/g
检查字符串开头和结尾的空格。
另请阅读