How to replace all Spaces in a String in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Replace all Spaces in a String #

Use the String.replaceAll() method to replace all spaces in a string, e.g. str.replaceAll(' ', '-');. The replaceAll method will return a new string where all occurrences of a space have been 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 arguments 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

We replace each space with a hyphen - in the example. However, you can provide whatever replacement string suits your use case, 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.

Alternatively, you can use the replace() method.

Use the String.replace() method to replace all spaces in a string, e.g. str.replace(/ /g, '+');. The replace() method will return a new string with all spaces replaced by the provided replacement.

index.js
const str = 'a b c'; const spacesReplaced = str.replace(/ /g, '+'); console.log(spacesReplaced); // 👉️ a+b+c

We passed the following arguments to the String.replace method:

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

The forward slashes / / mark the beginning and end of the regular expression.

Our regular expression consists of a single space.

We used the g (global) flag because we want to match all occurrences of a space in the string and not just the first occurrence.

We replaced all spaces with a plus + in the example. However, you could provide any replacement 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.