Thursday, January 29, 2026
HomeLanguagesJavascriptInsert a character after every n characters in JavaScript

Insert a character after every n characters in JavaScript

In this article, we are given a string and the task is to insert a character after every n character in that string.

There are two approaches, we will discuss below.

Method 1: Using substr(), push(), and join() Methods

In this approach, the string is broken into chunks by using substr() method and pushed to an array by the push() method. The array of chunks is returned which is then joined using the join() method on any character.

Example: This example shows the above-explained approach.

Javascript




let str = "A computer science portal for Geeks";
 
function insertCharacter(str, n) {
    let val = [];
    let i, l;
    for (i = 0, l = str.length; i < l; i += n) {
        val.push(str.substr(i, n));
    }
 
    return val;
};
 
console.log(insertCharacter(str, 5).join('@'));


Output

A com@puter@ scie@nce p@ortal@ for @Geeks

Method 2: Using RegExp and join() Method

In this approach, a RegExp is used which selects the parts of the string and then joined on any character using the join() method.

Example: This example shows the above-explained approach.

Javascript




let str = "A computer science portal for Geeks";
 
function gfg_Run() {
    console.log(str.match(/.{5}/g).join('@'));
}
 
gfg_Run();


Output

A com@puter@ scie@nce p@ortal@ for @Geeks
RELATED ARTICLES

Most Popular

Dominic
32475 POSTS0 COMMENTS
Milvus
122 POSTS0 COMMENTS
Nango Kala
6848 POSTS0 COMMENTS
Nicole Veronica
11978 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12065 POSTS0 COMMENTS
Shaida Kate Naidoo
6986 POSTS0 COMMENTS
Ted Musemwa
7221 POSTS0 COMMENTS
Thapelo Manthata
6934 POSTS0 COMMENTS
Umr Jansen
6916 POSTS0 COMMENTS