Insert a Character after every N Characters in JavaScript


Borislav Hadzhiev

Wed Nov 17 20212 min read


Photo by Sasha

Insert a Character after every N Characters #

To insert a character after every N characters, call the replace() method on the string, passing it the following regular expression - str.replace(/.{2}/g, '$&c'). The replace method will replace every 2 characters with the characters plus the provided replacement.

const str = 'ababab'; const result = str.replace(/.{2}/g, '$&c'); console.log(result); // ๐Ÿ‘‰๏ธ "abcabcabc"
If you're looking to avoid using regular expressions, scroll down to next subheading.

We passed 2 parameters to the String.replace method:

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

Let's start with the second parameter - the replacement.

The replacement string can include special replacement patterns.

In the example, the $& special pattern inserts the matched substring and we add the c character after that.

If we match ab, and replace the match using $&c, we are effectively replacing ab with abc.

The first parameter we passed to the replace method is the regular expression.

The forward slashes / / mark the beginning and end of the regex.

The dot . is a special character, that matches any single character.

The curly braces part, matches exactly N occurrences of the preceding character (the dot, which matches any single character).

We used the g (global) flag, because we want to match all occurrences of any 2 characters and not just the first occurrence.

In it's entirety, the replace method replaces every 2 characters with the 2 characters plus the c character, allowing us to insert a character after every 2 characters in the string.

Insert a Character after every N Characters using reduce #

To insert a character after every N characters:

  1. Split the string to an array
  2. Call the reduce() method on the array
  3. Check if the remainder of dividing the index by N is equal to 1.
  4. If the condition is met, add the character to the end of the string.
function insertAfterEveryN(str, char, n) { const result = str.split('').reduce((accumulator, current, index) => { if (index % n === 1) { return accumulator + current + char; } return accumulator + current; }, ''); return result; } // ๐Ÿ‘‡๏ธ "abcabcabc" console.log(insertAfterEveryN('ababab', 'c', 2));

The first step is to split the string into an array of characters using the String.split method.

// ๐Ÿ‘‡๏ธ ['a', 'b' ,'a' ,'b'] console.log('abab'.split(''))

We then use the Array.reduce method to iterate over the array.

We've provided an empty string as the initial value of the accumulator variable.

If dividing the index of the current iteration by N returns a remainder of 1, we know that we have to insert the character.

Otherwise, we add the letter of the current iteration to the accumulated string and return the result.

Which approach you pick is a matter of personal preference. In this scenario, I'd go with using the regex approach and I'd add comments concerning the second parameter, (maybe even the first one).

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