简体   繁体   中英

Replace Vowels in a String with their index in the String Using JavaScript

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.

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

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('');
}

You can try this mate.

 const vowel2index = str => str.replace(/[aeiou]/gi, (_, offset) => offset+1) console.log(vowel2index('this is my string')) 

PS : It will clear all test cases because i have already solved that kata. (Nice to see someone from codewars ♡) 😃

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM