✂️ 写一个方法去掉字符串中的空格

📅 发布于 2026年2月 | 👤 作者:博主 | 🏷️ 标签:字符串处理, 正则表达式, JavaScript, Web开发, 前端, 面试

欢迎来到我的博客文章!所有文章都是满满的前端干货,文章简明扼要。

方法一:使用 split 和 join

将字符串按空格分割成数组,然后再拼接回去:

function removeSpaces(str) {
    return str.split(" ").join("");
}

let str = "h e l l o   w o r l d";
console.log(removeSpaces(str)); // Output: "helloworld"

方法二:使用正则表达式(推荐)

使用正则表达式 /\s+/g 匹配所有空白字符:

function removeSpaces(str) {
    return str.replace(/\s+/g, '');
}

let str = "h e l l o   w o r l d";
console.log(removeSpaces(str)); // Output: "helloworld"

核心知识点

← 返回首页