views:

53

answers:

5

how to remove double white space using regexp (javascript) ?

var text = "My         name      is          Anas                 Fares";

result

var result = "My name is Anas Fares";

Maybe it needs regexp :)

How can i learn regexp because it is very hard. Are there any simple book ?

+1  A: 

You don't need a book, just a decent cheat sheet.

fredley
+4  A: 
text = text.replace(/\s{2,}/g, ' ');
  • \s will take all spaces, including new lines, so you may change that to / {2,}/g.
  • {2,} takes two or more. Unlike \s+, this will not replace a single space with a single space. (a bit of an optimization, but it usually makes a differance)
  • Finally, the g flag is needed in JavaScript, or it will only change the first block of spaces, and not all of them.
Kobi
Thank you, That what i need.
faressoft
A: 

in PCRE:

s/\s+/ /g

in JavaScript:

text = text.replace(/\s+/g, " ");
polemon
I wonder who voted me down.And what is wrong with my answer?
polemon
+2  A: 

try

result = str.replace(/^\s+|\s+$/g,'').replace(/\s+/g,' ');
Haim Evgi
+1 for trimming.
SLaks
+1  A: 
var str="this is    some text    with   lots  of    spaces!";
var result =str.replace(/\s+/," ");
Pavel Nikolov