Skip to main content

How to Insert a Character After Every N Characters in JavaScript

A common string formatting task is to insert a character or a substring at regular intervals within another string. For example, you might want to format a long serial number by inserting hyphens every four characters (12345678 -> 1234-5678-) or add a space to a credit card number. The most efficient and powerful way to achieve this is with the String.prototype.replace() method using a regular expression.

This guide will teach you how to use a simple regular expression to insert a character after every N characters in any string.

The Core Method: replace() with a Regular Expression

The replace() method, when used with a regular expression, can find patterns in a string and replace them with a new value. To insert a character, we can define a pattern that matches every "Nth" character group and then replace that group with itself plus the character we want to insert.

For example, you have a long string of characters and you want to break it up for readability by inserting a separator.

// Problem: How to insert a hyphen after every 4th character?
const serialNumber = '12345678ABCD';
// Desired Result: '1234-5678-ABCD-'

This solution uses a regular expression to match groups of four characters and a special replacement pattern ($&) to re-insert the matched group.

const serialNumber = '12345678ABCD';

// The regex /.{4}/g matches any four characters, globally.
// '$&-' replaces the match with itself ('$&') followed by a hyphen.
const formattedSerial = serialNumber.replace(/.{4}/g, '$&-');

console.log(formattedSerial); // Output: '1234-5678-ABCD-'
note

This is a concise, powerful, and efficient one-liner for solving the problem.

How the Regular Expression Works

Let's break down the two key components of this solution: the pattern and the replacement.

The Pattern: /.{4}/g

  • / ... /: These forward slashes mark the beginning and end of the regular expression.
  • .: This is a special character that matches any single character (except a newline).
  • {4}: This is a quantifier. It tells the regex engine to match exactly 4 occurrences of the preceding item (the .). So, .{4} means "match any four characters."
  • /g: This is the global flag. It is crucial. Without it, replace() would only match and replace the first group of four characters. The global flag ensures it finds all groups.

The Replacement Pattern: '$&-'

  • $&: This is a special replacement pattern in JavaScript. It is a back-reference that inserts the entire matched substring.
  • -: This is the literal hyphen we want to insert after the matched group.

So, when the regex finds '1234', the replacement pattern '$&-' tells the replace() method to replace it with '1234' + '-'.

Basic Example: Inserting a Hyphen

Here is the complete example in action.

const str = 'ABCDEFGHIJKL';
const charsToInsert = '-';
const everyNChars = 3;

// Create the regex dynamically
const regex = new RegExp(`.{${everyNChars}}`, 'g');

const result = str.replace(regex, `$&${charsToInsert}`);

console.log(result); // Output: 'ABC-DEF-GHI-JKL-'

Creating a Reusable Function

If you need to perform this operation frequently, it's a good practice to wrap the logic in a reusable function.

/**
* Inserts a character after every N characters in a string.
* @param {string} str - The original string.
* @param {number} n - The interval of characters.
* @param {string} charToInsert - The character to insert.
* @returns {string} The newly formatted string.
*/
function insertCharEveryN(str, n, charToInsert) {
// Use a RegExp object to dynamically create the pattern
const regex = new RegExp(`.{${n}}`, 'g');

// Use a lookbehind in the regex to avoid adding the char at the end
// This is a more advanced but cleaner approach
const advancedRegex = new RegExp(`(.{${n}})(?!$)`, 'g');

return str.replace(advancedRegex, `$1${charToInsert}`);
}

// Example Usage:
const serial = '12345678ABCD';
const formatted = insertCharEveryN(serial, 4, '-');
console.log(formatted); // Output: '1234-5678-ABCD'
note

Note on the Advanced Regex: The pattern (.{${n}})(?!$) is slightly more advanced.

  • (.{${n}}): This captures the group of N characters (so we can refer to it as $1).
  • (?!$): This is a negative lookahead. It asserts that the matched group is not followed by the end of the string ($). This is a clean way to prevent the final character from being added at the very end of the string.

Conclusion

Inserting characters at regular intervals is a formatting task perfectly suited for regular expressions.

  • The string.replace(/.{N}/g, '$&char') pattern is the most direct and efficient way to solve this problem.
  • Remember the key components:
    • .{N} matches N of any character.
    • The g flag is essential to replace all occurrences.
    • $& is the special replacement pattern that re-inserts the matched text.
  • For a cleaner result that avoids adding a character at the very end of the string, use a negative lookahead in your regex: /(.{N})(?!$)/g.