How to Remove All Whitespace from a String in JavaScript
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.
See also
- How to Remove All Vowels From a String in JavaScript
- How to Remove All Spaces from a String in JavaScript
- How to Remove a Class From All Elements in JavaScript
- How to Remove Special Characters From a String in JavaScript
- How to Check if String Contains Whitespace in JavaScript
- How to Add a Class to All Elements With JavaScript