-1

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
Community
  • 1
  • 1
Nil Jay
  • 35
  • 6

3 Answers3

1

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....
gavgrif
  • 15,194
  • 2
  • 25
  • 27
0

RegEx

Here, we can add a quantifier to . (which matches all chars except for new lines) and design an expression with one capturing group ($1):

(.{2})

Demo


JavaScript Demo

const regex = /(.{2})/gm;
const str = `AAAAAA`;
const subst = `$1bbb`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log('Substitution result: ', result);

RegEx Circuit

You can also visualize your expressions in jex.im:

enter image description here


If you wish to consider new lines as a char, then this expression would do that:

([\s\S]{2})

RegEx Demo

enter image description here

enter image description here

JavaScript Demo

const regex = /([\s\S]{2})/gm;
const str = `ABCDEF
GHIJK
LMNOP
QRSTU
VWXYZ
`;
const subst = `$1bbb`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log('Substitution result: ', result);
Emma
  • 27,428
  • 11
  • 44
  • 69
0

Try this:

const string1 = 'word'
console.log('Input:', string1)
const newStr = string1.replace(/(?<=(^(.{2})+))/g, 'gav')
console.log('Output:', newStr)
  • .{2}: 2 any character
  • (.{2})+: match 2 4 6 8 any character
  • ^(.{2})+: match 2 4 6 8 any character from start, if don't have ^, this regex will match from any position
  • ?<=(regex_group): match something after regex_group
  • g: match all

This way is finding 2,4,6, etc character from the start of the string and don't match this group so it will match '' before 2,4,6, etc character and replace with 'gav'

Example with word:

match wo, word and ignore it, match something before that('') and replace with 'gav' with method replace

hong4rc
  • 3,999
  • 4
  • 21
  • 40