Zulfiya Yumagulova
Zulfiya Yumagulova

Reputation: 11

How to insert string "av" between vowels JavaScript

I am writing a function which takes a string and should return modified string by adding "av" between every vowel in the string unless a vowel is proceed by another vowel. Her is my code but it doesn't work how I expect

text = text.toLowerCase()
for (let i = 0; i < text.length; i += 1) {
    text = text.replace(/([aeiou])([aeiou])/g, 'av')
 }
 return text
}

It returns "codingame" instead "cavodavingavamave"

Upvotes: 0

Views: 234

Answers (1)

zer00ne
zer00ne

Reputation: 43910

Try /(?<=[^aeiou])(?=[aeiou][^aeiou])/gm

  1. Lookbehind - must NOT match if preceded by vowels
  2. Lookahead - must be followed by a vowel and a non-vowel.

Lookarounds matches anything before and after a,e,i,o,u but doesn't include it in the returned match.

Regex101

const str = `codingame look`;

const rgx = new RegExp(/(?<=[^aeiou])(?=[aeiou][^aeiou])/, 'g');

let result = str.replace(rgx, 'av');

console.log(result);

Upvotes: 1

Related Questions