How to Replace all Hyphens in a String in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 12 20212 min read

Replace all Hyphens in a String in JavaScript #

To replace all hyphens in a string:

  1. Call the replaceAll() method, passing it a hyphen as the first parameter and the replacement string as the second.
  2. The replaceAll method returns a new string with all matches replaced by the provided replacement.
index.js
const str = 'a-b-c'; const hyphensReplaced = str.replaceAll('-', ' '); console.log(hyphensReplaced); // 👉️ a b c

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

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

In the example we replace each hyphen with a space, however you could provide any replacement that suits your use case, e.g. a dot .:

index.js
const str = 'a-b-c'; const hyphensReplaced = str.replaceAll('-', '.'); console.log(hyphensReplaced); // 👉️ a.b.c

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 versions 6-11. If you have to support the browser, use the replace method instead.

To replace all hyphens in a string:

  1. Call the replace() method, passing it a regular expression matching all hyphens as the first parameter and the replacement string as the second.
  2. The replace method will return a new string with all hyphens replaced with the provided replacement.
index.js
// Supported in IE 6-11 const str = 'a-b-c'; const hyphensReplaced = str.replace(/-/g, ' '); console.log(hyphensReplaced); // 👉️ a b c

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

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

We use the g (global) flag, because we want to match all hyphens in the string and not just the first occurrence.

The replace method does not mutate the original string, it returns a new string with one or more matches replaced.

The replaceAll method is quite nicer 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