我有额外的空格字符字符串。每次有一个以上的空白,我希望它是只有一个。我如何使用JavaScript做到这一点?
当前回答
使用带有replace函数的正则表达式可以做到这一点:
string.replace(/\s/g, "")
其他回答
就像这样:
Var s = " a b c "; console.log ( s.replace(/\s+/g, ' ') )
试试这个。
var string = " string 1";
string = string.trim().replace(/\s+/g, ' ');
结果将是
string 1
这里发生的事情是,它将首先使用trim()修剪外部空间,然后使用.replace(/\s+/g, ' ')修剪内部空间。
你可以扩充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();
这个怎么样?
“我的测试字符串\t\t与疯狂的东西很酷”。替换(/\s{2,9999}|\t/g, ' ')
输出"my test string with crazy stuff is cool "
这个也可以去掉任何标签
使用带有replace函数的正则表达式可以做到这一点:
string.replace(/\s/g, "")