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


当前回答

就像这样:

Var s = " a b c "; console.log ( s.replace(/\s+/g, ' ') )

其他回答

使用带有replace函数的正则表达式可以做到这一点:

string.replace(/\s/g, "")

就像这样:

Var s = " a b c "; console.log ( s.replace(/\s+/g, ' ') )

这个怎么样?

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

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

这个也可以去掉任何标签

下面是一个非正则表达式的解决方案(只是为了好玩):

Var s = ' a b word word。字,字,字'; //使用ES5: s = s.split (' ') .filter (n (n){返回函数 != '' }).加入(' '); console.log(年代);// "a b word word. "词,词,词" //或ES2015: S = S .split(' ')。Filter (n => n).join(' '); console.log(年代);// "a b word word. "词,词,词"

甚至可以用.filter(String)替换filter(n => n)

它用空格分隔字符串,从数组中删除所有空数组项(超过一个空格的数组项),并将所有单词再次连接到一个字符串中,在它们之间使用一个空格。

jQuery.trim()工作得很好。

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