我有额外的空格字符字符串。每次有一个以上的空白,我希望它是只有一个。我如何使用JavaScript做到这一点?


当前回答

试试这个。

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();

jQuery.trim()工作得很好。

http://api.jquery.com/jQuery.trim/

var x = "测试测试测试"。分割(" "). join (" "); 警报(x);

我假定您希望从字符串的开头和/或结尾删除空格(而不是删除所有空格?

如果是这样的话,你需要一个像这样的正则表达式:

mystring = mystring.replace(/(^\s+|\s+$)/g,' ');

这将删除字符串开头或结尾的所有空格。如果你只想从结尾开始修剪空格,那么正则表达式应该是这样的:

mystring = mystring.replace(/\s+$/g,' ');

希望这能有所帮助。

这个怎么样?

“我的测试字符串\t\t与疯狂的东西很酷”。替换(/\s{2,9999}|\t/g, ' ')

输出"my test string with crazy stuff is cool "

这个也可以去掉任何标签