Skip to content
Related Articles

Related Articles

Insert a character after every n characters in JavaScript
  • Last Updated : 31 Jul, 2020

Here given a string and the task is to insert a character after every n characters in that string. Here are 2 examples discussed below.

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

Example:




<!DOCTYPE HTML>  
<html>  
    <head
        <title
            Insert a character after 
          every n characters in JavaScript
        </title>
        <script src=
         </script
    </head
    <body style = "text-align:center;">  
        <h1 style = "color: green">  
            GeeksForGeeks  
        </h1>
        <p id = "GFG_UP">
        </p>
        <button onclick = "gfg_Run()"
            Click Here
        </button>
        <p id = "GFG_DOWN">
        </p>
        <script>
            var el_up = document.getElementById("GFG_UP");
            var el_down = document.getElementById("GFG_DOWN");
            var str = "A computer science portal for Geeks";
            el_up.innerHTML =  
"Click on the button to perform the operation.<br>'" + str + "'";
            function partition(str, n) {
                var retrn = [];
                var i, l;
                for(i = 0, l = str.length; i < l; i += n) {
                   retrn.push(str.substr(i, n));
                }
                return retrn;
            };
            function gfg_Run() {
                el_down.innerHTML = partition(str, 5).join('@');
            }
        </script> 
    </body>  
</html>

Output:



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

Example:




<!DOCTYPE HTML>  
<html>  
    <head
        <title
            Insert a character after 
         every n characters in JavaScript
        </title>
        <script src=
          </script
    </head
    <body style = "text-align:center;">  
        <h1 style = "color: green">  
            GeeksForGeeks  
        </h1>
        <p id = "GFG_UP">
        </p>
        <button onclick = "gfg_Run()"
            Click Here
        </button>
        <p id = "GFG_DOWN">
        </p>
        <script>
            var el_up = document.getElementById("GFG_UP");
            var el_down = document.getElementById("GFG_DOWN");
            var str = "A computer science portal for Geeks";
            el_up.innerHTML = 
 "Click on the button to perform the operation.<br>'" + str + "'";
            function gfg_Run() {
               el_down.innerHTML = str.match(/.{1, 5}/g).join('@');
            }
        </script
    </body>  
</html>

Output:

My Personal Notes arrow_drop_up
Recommended Articles
Page :