Reputation: 93
I need to replace each vowel in a string with its index + 1 within the string.
(Function name = vowel2index)
Output Example:
vowel2index('this is my string') == 'th3s 6s my str15ng'
I hope this example shows what I'm trying to do. I have tried using the replace method as follows:
str.replace(/[aeiou]/gi, str.indexOf(/[aeiou]/gi);
but that didn't come close to solving the problem. I also tried the code below, but I couldn't figure out where to go from the IF statement (I didn't use array vowels yet):
function vowel2index(str) {
let vowels = ["a", "e", "i", "o", "u"];
let arr = [];
for(i = 0; i < str.length; i++){
if (str[i] === /[aeiou]/gi) {
arr.push(str.replace(str[i], indexOf(str[i])+1));
}
Any help appreciated. As an FYI, this problem is from codewars.
Upvotes: 1
Views: 1165
Reputation: 37755
You can try this mate.
const vowel2index = str => str.replace(/[aeiou]/gi, (_, offset) => offset+1)
console.log(vowel2index('this is my string'))
P.S. : It will clear all test cases because i have already solved that kata. (Nice to see someone from codewars ♡) 😃
Upvotes: 1
Reputation: 32748
Nowhere near as clean as @CertainPerformance answer above but a brute-force solution is:
function vowel2index(string) {
var result = [];
for(var i = 0; i < string.length; i++) {
var c = string.charAt(i);
if(c.match(/[aeiou]/gi)) {
result.push(i + 1);
} else {
result.push(c);
}
}
return result.join('');
}
Upvotes: 1
Reputation: 370789
You're almost there. The .replace
function accepts an offset
parameter that contains the index of the current match, so you can just use the replacer function, and return that offset plus one. No need for an array of vowels, just use the character set of vowels in the pattern:
function vowel2index(str) {
return str.replace(/[aeiou]/gi, (vowel, offset) => offset + 1);
}
console.log(vowel2index('this is my string')); // == 'th3s 6s my str15ng');
Upvotes: 3
Reputation: 1545
Try this:
function vowel2index(str) {
for(i = 0; i < str.length; i++){
if (str[i] === /[aeiou]/gi) {
str.replace(str[i], indexOf(str[i])+1);
}
Upvotes: 0