给定一个这样的字符串:

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

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

目标:

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

当前回答

以下是对我来说很有效的解决方案:

var text = “ Tes ddas dMd WAlkman 3Dsfd ” .toLowerCase() .replace(/\b\s+/g, “ ”) .replace(/\b\w/g, s => s.toUpperCase()) .trimStart() .trimEnd(); 控制台.log(文本); 结果: Tes Ddas Dmd 随身听 3dsfd

其他回答

我有一个方法,我叫它Derp方法因为没有更好的名字。

while (str.indexOf("  ") !== -1) {
    str = str.replace(/  /g, " ");
}

在JSPerf中运行它会得到一些令人惊讶的结果,它击败了一些更复杂的方法EDIT原始JSPerf链接http://jsperf.com/removing-multiple-spaces/3当时似乎已经死了

更健壮的:

function trim(word)
{
    word = word.replace(/[^\x21-\x7E]+/g, ' '); // change non-printing chars to spaces
    return word.replace(/^\s+|\s+$/g, '');      // remove leading/trailing spaces
}
var string = "The dog      has a long   tail, and it     is RED!";
var replaced = string.replace(/ +/g, " ");

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

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

我们可以在sed system命令的帮助下使用下面的正则表达式。类似的正则表达式可用于其他语言和平台。

将文本添加到某个文件中,例如test

manjeet-laptop:Desktop manjeet$ cat test
"The dog      has a long   tail, and it     is RED!"

我们可以使用下面的正则表达式将所有空格替换为单个空格

manjeet-laptop:Desktop manjeet$ sed 's/ \{1,\}/ /g' test
"The dog has a long tail, and it is RED!"

希望这能起到作用

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

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