Remove the Underscores from a String in JavaScript

avatar

Borislav Hadzhiev

Fri Nov 19 20212 min read

banner

Photo by Charlie Hang

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.

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