I am working on an algorithm that takes in a string for input, and reverses the vowels of the string.
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?
You could do this in two phases:
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With