Remove the Underscores from a String in JavaScript

avatar

Borislav Hadzhiev

Last updated: Nov 19, 2021

banner

Photo from Unsplash

Remove the Underscores from a String #

To remove the underscores from a string, call the replaceAll() method on the string, passing it an underscore as the first parameter, and an empty string as the second, e.g. replaceAll('_', ''). The replaceAll method will return a new string, where all underscores are removed.

index.js
const str = 'a_b_c'; // ✅ Remove all underscores const result1 = str.replaceAll('_', ''); console.log(result1); // 👉️ "abc" // ✅ Remove all underscores using regex const result2 = str.replace(/_/g, ''); console.log(result2); // 👉️ "abc" // ✅ Remove only first underscore const result3 = str.replace(/_/, ''); console.log(result3); // 👉️ "ab_c"

The two parameters we passed to the String.replaceAll method are:

  1. the substring we want to match in the string
  2. the replacement for each match

By replacing each underscore with an empty string we practically remove the underscores from the string.

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

Alternatively, you can use the String.replace method.

To remove all the underscores from a string, call the replace() method on the string, passing it the following regular expression - /_/g, and replace each match of the regular expression with an empty string, e.g. str.replace(/_/g, '').

index.js
const str = 'a_b_c'; const result2 = str.replace(/_/g, ''); console.log(result2); // 👉️ "abc"

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

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

Our regular expression consists of a single underscore.

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.

Because we want to remove the underscores from the string, we replace each underscore with an empty string.

The only good reason I can think of to use the replace() method over replaceAll is that replace is supported in Internet Explorer, whereas replaceAll is not.

If you only want to replace the first occurrence of an underscore character, you simply have to remove the g (global) flag from the regular expression.

index.js
const str = 'a_b_c'; const result3 = str.replace(/_/, ''); console.log(result3); // 👉️ "ab_c"

By default, the replace method replaces the first occurrence of the match characters with the provided replacement.

By removing the g (global) flag, we only match the first underscore in the string.

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.