Remove all Whitespace from a String in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Remove all Whitespace from a String #

Use the String.replace() method to remove all whitespace from a string, e.g. str.replace(/\s/g, ''). The replace() method will remove all whitespace characters by replacing them with an empty string.

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 used the g (global) flag to specify that we want to match all occurrences of whitespace characters in the string, and not just the first occurrence.

The second parameter the replace() method takes is the replacement string.

For our purposes, we want to replace all whitespace characters with an empty string.

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

Alternatively, you can use the replaceAll() method.

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

The String.replaceAll method takes a string or a regular expression for the first parameter and a replacement string for the second.

In this particular scenario there is no benefit to using the `replaceAll()` method.

However, if you only need to remove spaces from the string (excluding tabs and newlines), you can pass a string instead of a regex to the replaceAll() method.

index.js
const str = ' A B C D '; const noWhitespace = str.replaceAll(' ', ''); console.log(noWhitespace); // 👉️ 'ABCD'
Instead of passing a regular expression to the replaceAll() method, we passed it a string containing a space.

The replaceAll() method removes all spaces by replacing them with empty strings.

Note that this approach only removes the spaces (not the tabs and newlines) from the string.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.