How to Remove all Hyphens from a String in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 23, 2022

banner

Photo from Unsplash

Remove all Hyphens from a String #

Use the replaceAll() method to remove all hyphens from a string, e.g. const hyphensRemoved = str.replaceAll('-', '');. The replaceAll method will remove all hyphens from the string by replacing them with empty strings.

index.js
const str = '1-2-3'; const hyphensRemoved = str.replaceAll('-', ''); console.log(hyphensRemoved); // 👉️ 123

We passed the following arguments 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 doesn't change the original string, it returns a new string with all matches replaced. Strings are immutable in JavaScript.

Alternatively, you can use the replace() method.

Use the String.replace() method to remove all hyphens from a string, e.g. const hyphensRemoved = str.replace(/-/g, '');. The replace() method will remove all hyphens from the string by replacing them with empty strings.

index.js
const str = '1-2-3'; const hyphensRemoved = str.replace(/-/g, ''); console.log(hyphensRemoved); // 👉️ 123

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

  1. a regular expression to match in the string
  2. a replacement for each match
The forward slashes / / mark the beginning and end of the regular expression.

We used the g (global) flag because we want to match all occurrences of a hyphen and not just the first occurrence.

To remove the hyphens from the string, we simply replace them with empty strings.

Further Reading #

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.