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
I am trying to create a program that adds "gav" after every second letter, when the string is written.
var string1 = "word"
wogavrdgav
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....
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})
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);
You can also visualize your expressions in jex.im:
If you wish to consider new lines as a char, then this expression would do that:
([\s\S]{2})
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);
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 allThis 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