How to replace all Spaces in a String in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 12 20212 min read

banner

Photo by Jorge Flores

Replace all Spaces in a String #

To replace all spaces in a string:

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

We passed the following parameters to the String.replaceAll method:

  1. the substring we want to match in the string, in our case a space
  2. the replacement for each match

In the example we replace each space with a dash -, however you can provide whatever replacement string you need, e.g. an empty string to remove all spaces.

index.js
const str = 'a b c'; const withoutSpaces = str.replaceAll(' ', ''); console.log(withoutSpaces); // ๐Ÿ‘‰๏ธ abc

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

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

To replace all spaces in a string:

  1. Call the replace() method, passing it a regular expression that matches all spaces as the first parameter and the replacement string as the second.
  2. The replace method will return a new string with all spaces replaced by the provided replacement.
index.js
// Supported in IE const str = 'a b c'; const spacesReplaced = str.replace(/ /g, '+'); console.log(spacesReplaced); // ๐Ÿ‘‰๏ธ a+b+c

We pass the following parameters to the String.replace method:

  1. A regular expression that matches all spaces
  2. The replacement string for each match

Our regular expression consists of a single space.

We use the g (global) flag, because we want to match all spaces in the string and not just the first occurrence.

In the example we replace all spaces with a plus +, however you could provide any replacement string.

The replace method is a bit less direct and intuitive than replaceAll in our scenario. However, if you have to support Internet Explorer it gets the job done.

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