Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
706 views
in Technique[技术] by (71.8m points)

javascript - 正则表达式用单个空格替换多个空格(Regex to replace multiple spaces with a single space)

Given a string like:

(给定一个像这样的字符串:)

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

What kind of jQuery or JavaScript magic can be used to keep spaces to only one space max?

(什么样的jQuery或JavaScript魔术可以用来将空间限制为最多一个空间?)

Goal:

(目标:)

"The dog has a long tail, and it is RED!"
  ask by AnApprentice translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Given that you also want to cover tabs, newlines, etc, just replace \s\s+ with ' ' :

(假设您还想覆盖制表符,换行符等,只需将\s\s+替换为' ' :)

string = string.replace(/ss+/g, ' ');

If you really want to cover only spaces (and thus not tabs, newlines, etc), do so:

(如果您真的只想覆盖空格(而不是制表符,换行符等),请这样做:)

string = string.replace(/  +/g, ' ');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...