Replace Underscores with Spaces in a String using JS

avatar

Borislav Hadzhiev

Sat Nov 20 20213 min read

banner

Photo by Zach Betten

Replace Underscores with Spaces in a String #

To replace the underscores with spaces in a string, call the replaceAll() method, passing it an underscore and space as parameters, e.g. str.replaceAll('_', ' '). The replaceAll method will return a new string where each underscores is replaced by a space.

index.js
const str = 'apple_pear_melon'; // βœ… without regular expression const result1 = str.replaceAll('_', ' '); console.log(result1); // πŸ‘‰οΈ "apple pear melon" // βœ… with regular expression const result2 = str.replace(/_+/g, ' '); console.log(result2); // πŸ‘‰οΈ "apple pear melon"
The replaceAll example replaces each underscore with a space, whereas the replace method replaces one or more underscores next to one another with a single space.

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

  1. a substring we want to match in the string
  2. the replacement for each match
The replaceAll method does not mutate the original string, it returns a new string. Strings are immutable in JavaScript.

An alternative approach is to use the String.replace method.

Replace Underscores with Spaces in a String using replace #

To replace the underscores with spaces in a string:

  1. Call the replace() method with the following regular expression - /_+/g.
  2. Replace each match with a string containing a space.
  3. The replace method will return a new string, where all underscores are replaced by spaces.
index.js
const str = 'apple_pear_melon'; const result2 = str.replace(/_+/g, ' '); console.log(result2); // πŸ‘‰οΈ "apple pear melon"

The first parameter we passed to the replace() method is a regular expression, and the second - the replacement for each match of the regex.

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

The regular expression matches an underscore.

The plus + matches the preceding item (the underscore) one or more times. In other words, we consider multiple underscores next to one another to be a single match, and replace them by a single space.

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

If you only want to replace the first underscore in the string with a space, remove the g flag.

index.js
const str = 'apple_pear_melon'; const replaceFirst = str.replace(/_+/, ' '); console.log(replaceFirst); // πŸ‘‰οΈ "apple pear_melon"

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

There might be an edge case that you have to handle - the string might start or end with an underscore, in which case you might want to remove the leading or trailing spaces.
index.js
// πŸ‘‡ ️starts and ends with underscore const str = '_apple_pear_melon_'; const result3 = str.replaceAll('_', ' ').trim(); console.log(result3); // πŸ‘‰οΈ "apple pear melon"

The String.trim method removes any leading or trailing whitespace from a string (spaces, tabs, newlines).

index.js
console.log(' apple '.trim()); // πŸ‘‰οΈ "apple"

To handle this edge case, we just call the trim() method after we have replaced the underscores with spaces.

Another commonly used alternative is to use the String.split and Array.join methods.

index.js
const str = '_apple_pear_melon_'; const result4 = str.split('_').join(' ').trim(); console.log(result4); // πŸ‘‰οΈ "apple pear melon"

The only parameter we passed to the split() method is the separator on which we want to split the string.

The method returns an array of substrings.

index.js
// πŸ‘‡οΈ ['one', 'two', 'three'] console.log('one_two_three'.split('_'));

Then we call the join() method on the array and pass a space as the separator.

index.js
// πŸ‘‡οΈ "one two three" console.log('one_two_three'.split('_').join(' '));
Which approach you pick is a matter of personal preference. I'd go with the replaceAll method, as I find it the most direct, readable and intuitive.

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