给定一个这样的字符串:
"The dog has a long tail, and it is RED!"
什么样的jQuery或JavaScript魔法可以用来保持空间只有一个最大空间?
目标:
"The dog has a long tail, and it is RED!"
给定一个这样的字符串:
"The dog has a long tail, and it is RED!"
什么样的jQuery或JavaScript魔法可以用来保持空间只有一个最大空间?
目标:
"The dog has a long tail, and it is RED!"
当前回答
我建议
string = string.replace(/ +/g," ");
对于空格或
string = string.replace(/(\s)+/g,"$1");
还可以将多个退货转换为单个退货。
其他回答
我建议
string = string.replace(/ +/g," ");
对于空格或
string = string.replace(/(\s)+/g,"$1");
还可以将多个退货转换为单个退货。
我们可以在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!"
希望这能起到作用
var string = "The dog has a long tail, and it is RED!";
var replaced = string.replace(/ +/g, " ");
或者如果你也想替换制表符:
var replaced = string.replace(/\s+/g, " ");
为了获得更多的控制,您可以使用replace回调来处理该值。
value = "tags:HUNT tags:HUNT tags:HUNT tags:HUNT"
value.replace(new RegExp(`(?:\\s+)(?:tags)`, 'g'), $1 => ` ${$1.trim()}`)
//"tags:HUNT tags:HUNT tags:HUNT tags:HUNT"
var str = "The dog has a long tail, and it is RED!";
str = str.replace(/ {2,}/g,' ');
编辑: 如果你想替换所有类型的空白字符,最有效的方法是这样的:
str = str.replace(/\s{2,}/g,' ');