Categories
JavaScript Answers jQuery

How to Remove Hyphens from a JavaScript String?

Spread the love

To remove hyphens from a JavaScript string, we can call the JavaScript string’s replace method.

For instance, we can write:

const str = "185-51-671";  
const newStr = str.replace(/-/g, "");  
console.log(newStr)

We call replace with a regex that matches all dashes with /-/ .

The g flag matches all instances of the pattern.

Then we replace all of them with empty strings as specified in the 2nd argument.

Therefore, newStr is '18551671' .

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *