admin管理员组

文章数量:1292069

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?

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?

Share Improve this question edited Nov 6, 2019 at 11:55 trincot 351k36 gold badges272 silver badges325 bronze badges asked May 11, 2016 at 18:45 nkr15nkr15 1493 silver badges8 bronze badges 2
  • 1 What if there are three sets of vowels? Would foobairbeu bee fuebiarboo? – tblznbits Commented May 11, 2016 at 18:55
  • Check this python script, you may get some ideas: gist.github./igniteflow/5026195 – Pedro Lobito Commented May 11, 2016 at 18:57
Add a ment  | 

1 Answer 1

Reset to default 10

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);

本文标签: javascriptReverse vowels in a stringusing regexStack Overflow