Open In App
Related Articles

Insert a character after every n characters in JavaScript

Improve Article
Improve
Save Article
Save
Like Article
Like

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

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 30 Jun, 2023
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials