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"
它將字符串按空格分隔,從數組中刪除所有空數組項(大于單個空格的項),然后將所有單詞再次連接到字符串中,并在它們之間使用單個空格。
添加回答
舉報