在 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.