Replace a Character with a Space using JavaScript

avatar

Borislav Hadzhiev

Last updated: Nov 19, 2021

banner

Check out my new book

Replace a Character with a Space in JavaScript #

Use the replaceAll() method to replace a character with a space. The method takes the character to be replaced and the replacement string as parameters, e.g. str.replaceAll('_', ' '). The method returns a new string with all occurrences of the character replaced by the provided replacement.

index.js
const str = 'apple_banana_kiwi'; // ✅️ replace all occurrences with a space const result1 = str.replaceAll('_', ' '); console.log(result1); // 👉️ "apple banana kiwi" // ✅️ replace only first occurrence with space const result2 = str.replace('_', ' '); console.log(result2); // 👉️ "apple banana_kiwi" // ✅️ replace all occurrences using regex const result3 = str.replace(/_/g, ' '); console.log(result3); // 👉️ "apple banana kiwi"

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

  1. the character we want to replace. We used an underscore in the example.
  2. the replacement for each match of the character
The replaceAll method does not change the original string, it returns a new string. Strings are immutable in JavaScript.

If you only need to replace the first occurrence of the character with a space, you can use the String.replace method instead.

By default, the method replaces the first occurrence of the string / regular expression.

index.js
const str = 'apple_banana_kiwi'; const result2 = str.replace('_', ' '); console.log(result2); // 👉️ "apple banana_kiwi"

The parameters are the same as with the replaceAll method - the string we want to match, and the replacement for each match.

If you need to replace a specific character using a regular expression, you can pass the regular expression as a parameter to the replace method.

For example, if you need to replace any digit, you'd want to use a regular expression.

index.js
const str = 'apple0banana1kiwi'; const result3 = str.replace(/[0-9]/g, ' '); console.log(result3); // 👉️ "apple banana kiwi"

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

The square brackets [] are called a character class and match the digit range from 0 to 9.

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

If you need help reading or writing a regular expression, check out this regex cheatsheet by the MDN docs, it has served me well over the years.

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.