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

Updated on: 19-Oct-2020

169 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements