Remove all Whitespace from a String in JavaScript

avatar

Borislav Hadzhiev

Thu Oct 07 20211 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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee