正则表达式用单个空格替换多个空格 [英] Regex to replace multiple spaces with a single space
本文介绍了正则表达式用单个空格替换多个空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出如下字符串:
"The dog has a long tail, and it is RED!"
可以使用哪种jQuery或JavaScript魔法将空格最多只保留一个空格?
What kind of jQuery or JavaScript magic can be used to keep spaces to only one space max?
目标:
"The dog has a long tail, and it is RED!"
推荐答案
鉴于您还要覆盖制表符,换行符等,只需用''$替换
\\\ +
c $ c>:
Given that you also want to cover tabs, newlines, etc, just replace \s\s+
with ' '
:
string = string.replace(/\s\s+/g, ' ');
如果你真的想要只覆盖空格(因而不是标签,换行符等),那么这样做:
If you really want to cover only spaces (and thus not tabs, newlines, etc), do so:
string = string.replace(/ +/g, ' ');
这篇关于正则表达式用单个空格替换多个空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文