Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse vowels in a string, using regex

I am working on an algorithm that takes in a string for input, and reverses the vowels of the string.

  • 'hello' should return as 'holle'
  • 'wookiE' should return as 'wEikoo'

Could str.replace be used as a solution?

function reverseVowels(str) {
    return str.replace(/[aeiou]/-g, /[aeiou]+1/);
}

I am not sure what the second parameter for the replace function would be. I intended to find the first vowel and then move on to the next one to replace it with. Can this be done just with this method or is a forEach/for loop needed?

like image 612
nkr15 Avatar asked Dec 25 '22 05:12

nkr15


1 Answers

You could do this in two phases:

  • extract the vowels into an array
  • perform the replace on the original string, calling a function on each match and popping the last vowel from the stack to replace it.

Code:

function reverseVowels(str){
   var vowels = str.match(/[aeiou]/g);
   return str.replace(/[aeiou]/g, () => vowels.pop());
}

// example
var original = 'James Bond';
var result = reverseVowels(original);

// output for snippet
console.log(original + ' => ' + result);
like image 72
trincot Avatar answered Dec 26 '22 19:12

trincot