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
216 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?

Goal:

"The dog has a long tail, and it is RED!"
question from:https://stackoverflow.com/questions/65845173/how-to-remove-more-than-one-whitespace-from-a-string-in-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
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 ss+ with ' ':

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

...