How to insert hyphens into a JavaScript string?

Sometimes, we want to insert hyphens into a JavaScript string.

In this article, we’ll look at how to insert hyphens into a JavaScript string.

How to insert hyphens into a JavaScript string?

To insert hyphens into a JavaScript string, we can use the JavaScript string’s replace method.

For instance, we write:

const phone = "1234567890";
const newPhone = phone.replace(/(d{3})(d{3})(d+)/, '$1-$2-$3');
console.log(newPhone)

We call phone.replace with a regex that has 3 capturing groups for capturing 2 groups of 3 digits and the remaining digits respectively.

Then we put dashes in between each group with '$1-$2-$3'.

Therefore, newPhone is '123-456-7890'.

Conclusion

To insert hyphens into a JavaScript string, we can use the JavaScript string’s replace method.