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.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.