Remove all Whitespace from a String in JavaScript

avatar

Borislav Hadzhiev

Thu Oct 07 20212 min read

banner

Photo by Vlad Bagacian

Remove all Whitespace from a String #

To remove all whitespace from a string, call the replace() method, passing it a regular expression that matches all whitespace characters and an empty string as replacement. For example, str.replace(/\s/g, '') returns a new string with all whitespace removed.

index.js
const str = ' A B C D '; const noWhitespace = str.replace(/\s/g, ''); console.log(noWhitespace); // 👉️ 'ABCD'

The first parameter we passed to the String.replace method is a regular expression.

The \s metacharacter matches spaces, tabs and newlines.

We use the g (global) flag to specify that we want to match all occurrences of whitespace characters in the string, not just the first occurrence.

The second parameter the replace function takes is the replacement. In our case we want to replace all whitespace with an empty string (nothing).

Note that the String.replace method does not change the original string, it returns a new string. Strings are immutable in JavaScript.

Further Reading #

Use the search field on my Home Page to filter through my more than 1,000 articles.