Insert a character at nth position in string in JavaScript

We are required to write a JavaScript function that takes in a string as the first argument and a number as the second argument and a single character as the third argument, let's call this argument char.

The number is guaranteed to be smaller than the length of the array. The function should insert the character char after every n characters in the string and return the newly formed string.

For example ?

If the arguments are ?

const str = 'NewDelhi';
const n = 3;
const char = ' ';

Then the output string should be ?

'Ne wDe lhi'

Method 1: Using Regular Expression

This approach uses regex to split the string into chunks and join them with the specified character:

const str = 'NewDelhi';
const n = 3;
const char = ' ';

const insertAtEvery = (str = '', num = 1, char = ' ') => {
    str = str.split('').reverse().join('');
    const regex = new RegExp('.{1,' + num + '}', 'g');
    str = str.match(regex).join(char);
    str = str.split('').reverse().join('');
    return str;
};

console.log(insertAtEvery(str, n, char));
Ne wDe lhi

Method 2: Using Substring and Loop

A more straightforward approach using a loop to build the result string:

function insertAtEveryN(str, n, insertChar) {
    let result = '';
    for (let i = 0; i < str.length; i++) {
        result += str[i];
        if ((i + 1) % n === 0 && i !== str.length - 1) {
            result += insertChar;
        }
    }
    return result;
}

console.log(insertAtEveryN('NewDelhi', 3, ' '));
console.log(insertAtEveryN('JavaScript', 2, '-'));
console.log(insertAtEveryN('HelloWorld', 5, '*'));
Ne wDe lhi
Ja-va-Sc-ri-pt
Hello*World

Method 3: Using Array and Join

This method splits the string into chunks using array operations:

function insertCharAtN(str, n, char) {
    const result = [];
    for (let i = 0; i < str.length; i += n) {
        result.push(str.substring(i, i + n));
    }
    return result.join(char);
}

console.log(insertCharAtN('NewDelhi', 3, ' '));
console.log(insertCharAtN('Programming', 4, '_'));
New Delh i
Prog_ramm_ing

Comparison

Method Readability Performance Best For
Regular Expression Complex Good Advanced users
Loop with Modulo High Excellent General use
Array and Join High Good Chunk-based insertion

Conclusion

The loop-based approach with modulo operator is the most readable and efficient method for inserting characters at regular intervals in a string. Choose the regex method for complex pattern matching scenarios.

Updated on: 2026-03-15T23:19:00+05:30

655 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements