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?
-
1
What if there are three sets of vowels? Would
foobairbeu
beefuebiarboo
? – 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
1 Answer
Reset to default 10You 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
版权声明:本文标题:javascript - Reverse vowels in a string, using regex - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741546385a2384619.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论