js实现空格
使用 split() 和 join() 方法
通过 split(' ') 将字符串按空格拆分为数组,再通过 join('') 合并为无空格的字符串。
const str = "hello world";
const result = str.split(' ').join('');
console.log(result); // "helloworld"
使用正则表达式替换
利用 replace() 方法配合正则表达式 /\s+/g 匹配所有空格并替换为空字符串。
const str = "hello world";
const result = str.replace(/\s+/g, '');
console.log(result); // "helloworld"
使用 trim() 移除首尾空格
trim() 仅移除字符串开头和结尾的空格,不处理中间的空格。
const str = " hello world ";
const result = str.trim();
console.log(result); // "hello world"
遍历字符串手动过滤空格
通过循环遍历字符串,将非空格字符拼接为新字符串。
const str = "hello world";
let result = '';
for (let i = 0; i < str.length; i++) {
if (str[i] !== ' ') {
result += str[i];
}
}
console.log(result); // "helloworld"
使用 replaceAll() 方法(ES2021+)
直接替换所有空格字符,需注意浏览器兼容性。

const str = "hello world";
const result = str.replaceAll(' ', '');
console.log(result); // "helloworld"
注意事项
- 正则表达式
\s匹配所有空白字符(包括空格、制表符、换行符等)。 replaceAll仅在现代浏览器中支持,旧环境需使用正则表达式替代。






