示例 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
检查字符串中的空格。