给定一个这样的字符串:

"The dog      has a long   tail, and it     is RED!"

什么样的jQuery或JavaScript魔法可以用来保持空间只有一个最大空间?

目标:

"The dog has a long tail, and it is RED!"

当前回答

var myregexp = new RegExp(/ {2,}/g);

str = str.replace(myregexp,' ');

其他回答

我知道我迟到了,但我发现了一个很好的解决方案。

下面就是:

var myStr = myStr.replace(/[ ][ ]*/g, ' ');
var string = "The dog      has a long   tail, and it     is RED!";
var replaced = string.replace(/ +/g, " ");

或者如果你也想替换制表符:

var replaced = string.replace(/\s+/g, " ");

这是一种解决方案,尽管它将针对所有空格字符:

"The      dog        has a long tail,      and it is RED!".replace(/\s\s+/g, ' ')

"The dog has a long tail, and it is RED!"

编辑:这可能更好,因为它的目标是一个空格后面跟着一个或多个空格:

"The      dog        has a long tail,      and it is RED!".replace(/  +/g, ' ')

"The dog has a long tail, and it is RED!"

替代方法:

"The      dog        has a long tail,      and it is RED!".replace(/ {2,}/g, ' ')
"The dog has a long tail, and it is RED!"

我没有单独使用/\s+/,因为它可以多次替换跨越1个字符的空格,而且可能效率较低,因为它的目标超过了必要的范围。

我没有深入测试任何这些,所以如果有bug,我就不知道了。

另外,如果你要做字符串替换,记得重新分配变量/属性到它自己的替换,例如:

var string = 'foo'
string = string.replace('foo', '')

使用jQuery.prototype.text:

var el = $('span:eq(0)');
el.text( el.text().replace(/\d+/, '') )
var myregexp = new RegExp(/ {2,}/g);

str = str.replace(myregexp,' ');

假设你还想覆盖制表符、换行符等,只需将\s\s+替换为' ':

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

如果你真的只想覆盖空格(而不是制表符,换行符等),可以这样做:

string = string.replace(/  +/g, ' ');