题目:
Simple, remove the spaces from the string, then return the resultant string.
个人感觉不错的解答:
function noSpace(x){
return x.replace(/\s/g, '');
}
function noSpace(x){return x.split(' ').join('')}
const noSpace = x => x.replace(/ /g, "");
自己的解答:
function noSpace(x) {
return x.replace(/[ ]/g, '');
}
涉及到的知识点:
string.replace MDN
RegExp
replace() 方法返回一个由替换值(replacement)替换一些或所有匹配的模式(pattern)后的新字符串。模式可以是一个字符串或者一个正则表达式,替换值可以是一个字符串或者一个每次匹配都要调用的回调函数。
原字符串不会改变。

在进行全局的搜索替换时,正则表达式需包含 g 标志。

本文探讨了在JavaScript中去除字符串中空格的几种有效方法,包括使用replace()函数结合正则表达式,以及split和join方法。通过具体代码示例展示了不同实现方式,并解释了replace()方法的工作原理。
523

被折叠的 条评论
为什么被折叠?



