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
Deleting the last vowel from a string in JavaScript
We are required to write a JavaScript function that takes in a string and returns a new string with the last vowel of each word removed.
For example: If the string is ?
const str = 'This is an example string';
Then the output should be ?
const output = 'Ths s n exampl strng';
Therefore, let's write the code for this function ?
Example
The code for this will be ?
const str = 'This is an example string';
const removeLast = word => {
const lastIndex = el => word.lastIndexOf(el);
const ind = Math.max(lastIndex('a'), lastIndex('e'), lastIndex('i'), lastIndex('o'), lastIndex('u'));
return word.substr(0, ind) + word.substr(ind+1, word.length);
}
const removeLastVowel = str => {
const strArr = str.split(' ');
return strArr.reduce((acc, val) => {
return acc.concat(removeLast(val));
}, []).join(' ');
};
console.log(removeLastVowel(str));
Output
The output in the console will be ?
Ths s n exampl strng
How It Works
The solution works in two steps:
1. removeLast function: For each word, it finds the last occurrence of each vowel (a, e, i, o, u) using lastIndexOf(). Then Math.max() determines which vowel appears last in the word. Finally, it removes that vowel using substr().
2. removeLastVowel function: Splits the input string into words, applies removeLast to each word using reduce(), and joins the results back into a string.
Alternative Approach Using Regular Expression
const str = 'This is an example string';
const removeLastVowelRegex = str => {
return str.split(' ').map(word => {
// Find last vowel position
let lastVowelIndex = -1;
for (let i = word.length - 1; i >= 0; i--) {
if (/[aeiouAEIOU]/.test(word[i])) {
lastVowelIndex = i;
break;
}
}
if (lastVowelIndex !== -1) {
return word.slice(0, lastVowelIndex) + word.slice(lastVowelIndex + 1);
}
return word;
}).join(' ');
};
console.log(removeLastVowelRegex(str));
Ths s n exampl strng
Conclusion
Both approaches effectively remove the last vowel from each word. The first method uses Math.max() with lastIndexOf(), while the second uses a loop to find the last vowel. Choose based on your preference for readability versus performance.
