How can I insert a character after every n characters in javascript?

Solution 1:

With regex

"The quick brown fox jumps over the lazy dogs.".replace(/(.{5})/g,"$1$")

The q$uick $brown$ fox $jumps$ over$ the $lazy $dogs.$

cheers,

Solution 2:

function chunk(str, n) {
    var ret = [];
    var i;
    var len;

    for(i = 0, len = str.length; i < len; i += n) {
       ret.push(str.substr(i, n))
    }

    return ret
};

chunk("The quick brown fox jumps over the lazy dogs.", 5).join('$');
// "The q$uick $brown$ fox $jumps$ over$ the $lazy $dogs."

Solution 3:

Keep it simple

  var str = "123456789";
  var parts = str.match(/.{1,3}/g);
  var new_value = parts.join("-"); //returns 123-456-789

Solution 4:

let s = 'The quick brown fox jumps over the lazy dogs.';
s.split('').reduce((a, e, i)=> a + e + (i % 5 === 4 ? '$' : ''), '');

Explain: split('') turns a string into an array. Now we want to turn the array back to one single string. Reduce is perfect in this scenario. Array's reduce function takes 3 parameters, first is the accumulator, second is the iterated element, and the third is the index. Since the array index is 0 based, to insert after 5th, we are looking at index i%5 === 4.