示例 1:使用 split() 和 join()
// program to trim a string
const string = ' Hello World ';
const result = string.split(' ').join('');
console.log(result);
输出
HelloWorld
在上面的程序中,
split(' ')
方法用于将 字符串 分割成单独的数组元素。["", "", "", "", "", "", "Hello", "World", "", "", "", "", "", "", ""]
join('')
方法将数组合并成一个字符串。
示例 2:使用正则表达式
// program to trim a string
function trimString(x) {
const result = x.replace(/\s/g,'');
return result
}
const result = trimString(' Hello World ');
console.log(result);
输出
HelloWorld
在上面的程序中,使用正则表达式和 replace() 方法来删除文本中的所有空格。
/\s/g
检查字符串中的空格。
另请阅读