Removing last vowel - 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';

Example

Following is the code −

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

Following is the output in the console −

Ths s n exampl strng

Updated on: 18-Sep-2020

233 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements