Replacing vowels with their 1-based index in a string in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in a string and replaces all occurrences of the vowels in the string with their index in the string (1-based).

It means if the second letter of the string is a vowel, it should be replaced by 2.

Example

Following is the code −

 Live Demo

const str = 'cancotainsomevowels';
const replaceVowels = (str = '') => {
   const vowels = 'aeiou';
   let res = '';
   for(let i = 0; i < str.length; i++){
      const el = str[i];
      if(vowels.includes(el)){  
         res += (i + 1);
      }else{
         res += el;
      };
   };
   return res;
};
console.log(replaceVowels(str));

Output

Following is the console output −

c2nc5t78ns11m13v15w17ls
raja
Published on 19-Apr-2021 08:12:34
Advertisements