How to Remove All Whitespace from a String in JavaScript

Last updated on June 20, 2022
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.

Coding Beauty Assistant logo

Try Coding Beauty AI Assistant for VS Code

Meet the new intelligent assistant: tailored to optimize your work efficiency with lightning-fast code completions, intuitive AI chat + web search, reliable human expert help, and more.

See also