Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Replacing vowels with their 1-based index in a string in JavaScript
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 ?
const str = 'cancotainsomevowels';
const replaceVowels = (str = '') => {
const vowels = 'aeiou';
let res = '';
for(let i = 0; i
Output
Following is the console output ?
c2nc5t78ns11m13v15w17ls
Alternative Approach Using Array Methods
We can also solve this using array methods like split() and map():
const str = 'hello world';
const replaceVowelsWithMap = (str = '') => {
const vowels = 'aeiouAEIOU';
return str
.split('')
.map((char, index) => vowels.includes(char) ? index + 1 : char)
.join('');
};
console.log(replaceVowelsWithMap(str));
console.log(replaceVowelsWithMap('EDUCATION'));
h2ll4 w6rld
2DUC6T71012
How It Works
The function works by:
- Iterating through each character in the string
- Checking if the character is a vowel (a, e, i, o, u)
- If it's a vowel, replacing it with its 1-based index position
- If it's not a vowel, keeping the original character
Conclusion
Both approaches effectively replace vowels with their 1-based position. The loop method is more straightforward, while the array method offers a functional programming style for the same result.
Advertisements
