How to remove double space character with regexp?

Input:

". . . . ." 

Expected Result:

 ". . . . ." 
+4
source share
4 answers
 text = text.replace(/\s{2,}/g, ' '); 
  • \s will accept all spaces, including newlines, so you can change this to / {2,}/g .
  • {2,} takes two or more. Unlike \s+ , this does not replace one space with one space. (a bit of optimization, but usually it makes a difference).
  • Finally, the g flag is required in JavaScript, or it will only change the first block of spaces, not all of them.
+20
source

try

 result = str.replace(/^\s+|\s+$/g,'').replace(/\s+/g,' '); 
+2
source
 var str="this is some text with lots of spaces!"; var result =str.replace(/\s+/," "); 
+1
source

in PCRE:

 s/\s+/ /g 

in javascript:

 text = text.replace(/\s+/g, " "); 
0
source

All Articles