Search code examples
javascriptregexstringregex-groupregex-greedy

How to append a string to another string after every N char?


I am trying to create a program that adds "gav" after every second letter, when the string is written.

var string1  = "word"

Expected output:

wogavrdgav

Solution

  • You can use the modulus operator for this -

    var string1  = "word";
    
    function addGav(str){
      var newStr = '';
      var strArr = str.split('');
    
      strArr.forEach(function(letter, index){
        index % 2 == 1
          ? newStr += letter + 'gav'
          : newStr += letter
      })
      return newStr;
    }
    
    console.log(addGav(string1)); // gives wogavrdgav
    
    console.log(addGav('gavgrif')) //gives gagavvggavrigavf....