Open In App

Insert a character after every n characters in JavaScript

Improve
Improve
Like Article
Like
Save
Share
Report

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


Last Updated : 30 Jun, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads