Insert a Character after every N Characters in JavaScript


Borislav Hadzhiev

Last updated: Jul 23, 2022


Photo from Unsplash

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 the following 2 arguments 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, to which we add the c character.

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

The first argument 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, match 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.

The initial value of the accumulator variable is an empty string because that's what we provided as the second argument to the method.

If dividing the index of the current iteration by N returns a remainder of 1, then 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. I'd go with the regex and I'd add comments regarding the second parameter, (maybe even the first one).

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.