Friday, December 27, 2024
Google search engine
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

Recent Comments