Remove all Spaces from a String in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 12 20212 min read

banner

Photo by Evelyn Paris

Remove all Spaces from a String #

To remove all spaces from a string:

  1. Call the replaceAll method, passing it a string containing a space as the first parameter and an empty string as the second - str.replaceAll(' ', '').
  2. The replaceAll method returns a new string with all of the matches replaced.
index.js
const str = 'a b c'; const replaced = str.replaceAll(' ', ''); console.log(replaced); // ๐Ÿ‘‰๏ธ 'abc'

The parameters we passed to the String.replaceAll method are:

  1. a substring we want to match in the string. In our case we want to match all spaces in the string.
  2. the replacement string - for our purposes an empty string
Because we want to remove all spaces, we just replace them with an empty string.

Note that the replaceAll method does not change the contents of the original string, it returns a new string with the matches replaced. Strings are immutable in JavaScript.

The replaceAll method is not supported by Internet Explorer versions 6-11. If you need to support the browser, use the replace method instead.

To remove all spaces from a string:

  1. Call the replace method, passing it a regular expression matching all spaces as the first parameter and an empty string as the second.
  2. The replace method will return a new string, which contains no spaces.
index.js
// Supported in IE 6-11 const str = 'a b c'; const replaced = str.replace(/ /g, ''); console.log(replaced); // ๐Ÿ‘‰๏ธ abc

The String.replace method takes the following parameters:

  1. a regular expression we want to match in the string, in our case a space.
  2. the replacement string, in our case an empty string

We use the g (global) flag, because we want to match all occurrences of a space and not just the first one.

The replace method does not change the original string, it returns a new string with one or more matches replaced.

Note that this regular expression does not match tabs and new lines. If you want to remove all spaces, tabs and new lines do this instead:

index.js
const str = 'a b c'; const replaced = str.replace(/\s/g, ''); console.log(replaced); // ๐Ÿ‘‰๏ธ abc

We use the \s character in the regex. The special character matches spaces, tabs and new lines.

If you ever need a regex cheasheet, I've found the MDN cheatsheet to be the best.

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