Categories
JavaScript Answers

How to insert a character after every n characters in JavaScript?

Spread the love

Sometimes, we want to insert a character after every n characters in JavaScript.

In this article, we’ll look at how to insert a character after every n characters in JavaScript.

How to insert a character after every n characters in JavaScript?

To insert a character after every n characters in JavaScript, we can use the string’s match and array join methods.

For instance, we write

const str = "123456789";
const parts = str.match(/.{1,3}/g);
const newValue = parts.join("-");

to call str.match with a regex that matches all groups of 3 digits and return the matches in an array.

Then we call join with '-' to join the matches text with '-'.

Conclusion

To insert a character after every n characters in JavaScript, we can use the string’s match and array join methods.

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 *