给定一个这样的字符串:

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

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

目标:

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

当前回答

鼠标指针碰到.replace(美元/ ^ \ s + | \ s + | (\ s) + / g, 1美元)应该做的诀窍!

其他回答

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

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

如果你不想使用replace(替换字符串中的空格而不使用replace javascript),这里有一个替代解决方案。

var str=“狗有一条长尾巴,而且是红色的!”; var = / \ s规则{1,}/ g; STR = STR .split(规则)。加入(" "); document . write (str);

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

编辑: 如果你想替换所有类型的空白字符,最有效的方法是这样的:

str = str.replace(/\s{2,}/g,' ');

我知道我们必须使用正则表达式,但在一次采访中,我被要求不要使用正则表达式。

@slightlytyler帮助我提出了下面的方法。

const testStr = "I LOVE STACKOVERFLOW LOL"; const removeSpaces = str => { Const chars = str.split("); const nextChars = char .reduce( (acc, c) => { If (c === ' ') { const lastChar = acc[acc.]长度- 1]; if (lastChar === ' ') { 返回acc; } } 返回[…acc, c]; }, [], ); const nextStr = nextchar .join("); 返回nextStr }; console.log (removeSpaces (testStr));

尝试用一个空格替换多个空格。

<script type="text/javascript">
    var myStr = "The dog      has a long   tail, and it     is RED!";
    alert(myStr);  // Output 'The dog      has a long   tail, and it     is RED!'

    var newStr = myStr.replace(/  +/g, ' ');
    alert(newStr);  // Output 'The dog has a long tail, and it is RED!'
</script>

阅读更多@用单个空格替换多个空格