移除最後一個母音 - 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

更新時間: 18-Sep-2020

316 次瀏覽

開啟你的 職業生涯

透過完成課程成為認證人員

開始
廣告
© . All rights reserved.