replace(/\s+/g,' ');
reduces all whitespace to one space, including breaks. Sometime I have more than 1 spaces what I want to reduce to one, keeping the new lines, breaks.
Asked
Active
Viewed 296 times
2

zsola3075457
- 177
- 4
- 14
-
I dont know what are tabs, in this text fields are only that kind of breaks, when you hit the enter key. – zsola3075457 Dec 06 '13 at 21:03
-
I see you used \s in your regex. `\s` is a whitespace character and represents `[\ \t\r\n\f]`, none of which you can see, and of which, space is only one of a possible 5 in the class. Tab being another one. – Dec 07 '13 at 22:45
1 Answers
2
You should use:
string = string.replace(/ {2,}/g, ' ');
\s
matches all white-spaces including newlines.
OR using lookahead:
string = string.replace(/ +(?= )/g, '');

Tim Pietzcker
- 328,213
- 58
- 503
- 561

anubhava
- 761,203
- 64
- 569
- 643
-
-
My own preference is for lookahead based regex but I believe both will behave same. – anubhava Dec 06 '13 at 20:58