Insert a Character after every N characters in JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 4, 2024
4 min

banner

# Insert a Character after every N Characters in JavaScript

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.

index.js
const str = 'ababab'; const result = str.replace(/.{2}/g, '$&c'); console.log(result); // ๐Ÿ‘‰๏ธ "abcabcabc"

insert character every n characters

The code for this article is available on GitHub

The String.replace() method returns a new string with one, some, or all matches of a regular expression replaced with the provided replacement.

The method takes the following parameters:

NameDescription
patternThe pattern to look for in the string. Can be a string or a regular expression.
replacementA string used to replace the substring match by the supplied pattern.

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 added the c character.
index.js
const str = 'ababab'; const result = str.replace(/.{2}/g, '$&c'); console.log(result); // ๐Ÿ‘‰๏ธ "abcabcabc"

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 and 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.

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

This is a four-step process:

  1. Split the string into an array.
  2. Use the reduce() method to iterate over 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.
index.js
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));

insert character after every n characters using reduce

The code for this article is available on GitHub

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

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

The function we passed to the Array.reduce() method gets called for each element in 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.

The value we return from the callback function gets passed as the accumulator on the next iteration.

# Insert a Character after every N characters using match

You can also use the match method to insert a character after every N characters.

index.js
const str = 'ababab'; const matches = str.match(/.{1,2}/g); console.log(matches); // ๐Ÿ‘‰๏ธ [ 'ab', 'ab', 'ab' ] const result = matches.join('c'); console.log(result); // ๐Ÿ‘‰๏ธ abcabcab

insert character after every n characters using match

The code for this article is available on GitHub

The String.match() method matches a string against a regular expression.

The method returns an array containing the matches (if any) or null if no matches are found.

The forward slashes / / mark the beginning and end of the regular expression.

The dot . is a special character and matches any single character.

The {n,m} syntax matches at least n and most m occurrences of the preceding item (any character).

index.js
const str = 'ababab'; const matches = str.match(/.{1,2}/g); console.log(matches); // ๐Ÿ‘‰๏ธ [ 'ab', 'ab', 'ab' ]

Once we get an array of the matches, we join them with the characters we want to insert as the separator.

index.js
const str = 'ababab'; const matches = str.match(/.{1,2}/g); console.log(matches); // ๐Ÿ‘‰๏ธ [ 'ab', 'ab', 'ab' ] const result = matches.join('c'); console.log(result); // ๐Ÿ‘‰๏ธ abcabcab
The code for this article is available on GitHub

The Array.join() method concatenates all of the elements in an array using a separator.

The only argument the Array.join() method takes is a separator - the string used to separate the elements of the array.

If a value for the separator argument is omitted, the array elements are joined with a comma ,.

If the separator argument is set to an empty string, the array elements are joined without any characters in between them.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev