在 JavaScript 中删除字符串中的最后一个元音


我们需要编写一个 JavaScript 函数,它以一个字符串作为输入,并返回一个新的字符串,其中删除了每个单词的最后一个元音。

例如:如果字符串为 -

const str = 'This is an example string';

那么输出应该为 -

const output = 'Ths s n exampl strng';

因此,让我们编写此函数的代码 -

示例

代码如下 -

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));

输出

控制台中的输出为 -

Ths s n exampl strng

更新于: 2020 年 10 月 19 日

211 次浏览

开启您的 职业生涯

完成课程即可获得认证

开始
广告
© . All rights reserved.