Replace all whitespace characters

Sourav picture Sourav · Jun 28, 2011 · Viewed 196.9k times · Source

I want to replace all occurrences of white space characters (space, tab, newline) in JavaScript.
How to do so?

I tried:

str.replace(/ /gi, "X")

Answer

Alex K. picture Alex K. · Jun 28, 2011

You want \s

Matches a single white space character, including space, tab, form feed, line feed.

Equivalent to

[ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]

in Firefox and [ \f\n\r\t\v] in IE.


str = str.replace(/\s/g, "X");