Replace all whitespace characters

Viewed 228262

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")
10 Answers

If you use

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

it replaces all whitespaces. For example:

var str = "hello my world";
str.replace(/\s/g, "") //the result will be "hellomyworld"

You could use the function trim

let str = ' Hello World ';

alert (str.trim());

All the front and back spaces around Hello World would be removed.

Related