How to Remove all Hyphens from a String in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 12 20212 min read

banner

Photo by Larm Rmah

Remove all Hyphens from a String #

To remove all hyphens from a string:

  1. Call the replaceAll() method, passing it a hyphen as the first parameter and an empty string as the second - replaceAll('-', '').
  2. The replaceAll method returns a new string with all matches replaced by the provided replacement.
index.js
const str = '1-2-3'; const hyphensRemoved = str.replaceAll('-', ''); console.log(hyphensRemoved); // ๐Ÿ‘‰๏ธ 123

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

  1. a substring we need to match in the string, in our case a hyphen -
  2. a replacement string for each match

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

The replaceAll method is not supported in Internet Explorer. If you have to support the browser, use the replace method instead.

To remove all hyphens from a string:

  1. Call the replace() method, passing it a regular expression that matches all hyphens as the first parameter and an empty string as the second.
  2. The replace method will return a new string containing no hyphens.
index.js
const str = '1-2-3'; const hyphensRemoved = str.replace(/-/g, ''); console.log(hyphensRemoved); // ๐Ÿ‘‰๏ธ 123

We passed the following parameters to the String.replace method:

  1. a regular expression to match in the string
  2. a replacement for each match

We use the g (global) flag in the regular expression, because we want to match all hyphens and not just the first occurrence of a hyphen.

The replaceAll method is a bit more elegant and easier to read, however if you have to support Internet Explorer, the replace method gets the job done.

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