Replace all whitespace characters

Replace all whitespace characters

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”)

Solutions/Answers:

Solution 1:

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");

Solution 2:

\s is a meta character that covers all white space. You don’t need to make it case-insensitive — white space doesn’t have case.

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

Solution 3:

We can also use this if we want to change all multiple joined blank spaces with a single character:

str.replace(/\s+/g,'X');

Solution 4:

Have you tried the \s?

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

Solution 5:

Try this:

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

EDIT (correct version without typo):

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

Solution 6:

Actually it has been worked but

just try this.

take the value /\s/g into a string variable like

String a = /\s/g;

str = str.replaceAll(a,"X");