Fri Nov 19 2021·2 min read
Photo by Anneliese Phillips
replaceAll() method to replace a character with a space. The method
takes the character to be replaced and the replacement string as parameters,
str.replaceAll('_', ' '). The method returns a new string with all
occurrences of the character replaced by the provided replacement.
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:
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.
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
For example, if you need to replace any digit, you'd want to use a regular expression.
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
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'll send you 1 email a week with links to all of the articles I've written that week