4 回答
TA贡献1877条经验 获得超6个赞
您可以扩展String以将这些行为实现为方法,如下所示:
String.prototype.killWhiteSpace = function() {
return this.replace(/\s/g, '');
};
String.prototype.reduceWhiteSpace = function() {
return this.replace(/\s+/g, ' ');
};
现在,您可以使用以下优雅的形式来生成所需的字符串:
"Get rid of my whitespaces.".killWhiteSpace();
"Get rid of my extra whitespaces".reduceWhiteSpace();
TA贡献1844条经验 获得超8个赞
这是一个非正则表达式的解决方案(只是为了好玩):
var s = ' a b word word. word, wordword word ';
// with ES5:
s = s.split(' ').filter(function(n){ return n != '' }).join(' ');
console.log(s); // "a b word word. word, wordword word"
// or ES6:
s = s.split(' ').filter(n => n).join(' ');
console.log(s); // "a b word word. word, wordword word"
它将字符串按空格分隔,从数组中删除所有空数组项(大于单个空格的项),然后将所有单词再次连接到字符串中,并在它们之间使用单个空格。
添加回答
举报
