To remove all whitespace from a string in JavaScript, call the replace()
method on the string, passing a regular expression that matches any whitespace character, and an empty string as a replacement. For example, str.replace(/\s/g, ''
) returns a new string with all whitespace removed from str
.
const str = '1 2 3';
const whitespaceRemoved = str.replace(/\s/g, '');
console.log(whitespaceRemoved); // 123
The \s
regex metacharacter matches whitespace characters, such as spaces, tabs, and newlines.
We use the g
regex flag to specify that all whitespace characters in the string should be matched. Without this flag, only the first whitespace will be matched and replaced:
const str = '1 2 3';
// No 'g' flag in regex
const whitespaceRemoved = str.replace(/\s/, '');
// Only first whitespace removed
console.log(whitespaceRemoved); // 12 3
The replace()
method returns a new string with all the matches replaced with the second argument passed to it. We pass an empty string (''
) as the second argument to replace all the whitespace with nothing, which effectively removes them.
Note
replace()
returns a new string without modifying the original string, as strings in JavaScript are immutable.
const str = '1 2 3';
const whitespaceRemoved = str.replace(/\s/g, '');
console.log(whitespaceRemoved); // 123
// Not modified
console.log(str); // 1 2 3
Every Crazy Thing JavaScript Does
A captivating guide to the subtle caveats and lesser-known parts of JavaScript.