從特定字元開始反轉單詞 - JavaScript


我們需要編寫一個 JavaScript 函式,該函式輸入一個句子字串和一個字元,並且該函式應反轉字串中所有以該特定字元開頭的單詞。

比如:如果字串為 -

const str = 'hello world, how are you';

以特定字元 'h' 開頭 -

那麼輸出字串應為 -

const output = 'olleh world, woh are you';

這意味著,我們已經反轉了以 “h” 開頭的單詞,即 Hello 和 How。

示例

以下是程式碼 -

const str = 'hello world, how are you';
const reverseStartingWith = (str, char) => {
   const strArr = str.split(' ');
   return strArr.reduce((acc, val) => {
      if(val[0] !== char){
         acc.push(val);
         return acc;
      };
      acc.push(val.split('').reverse().join(''));
      return acc;
   }, []).join(' ');
};
console.log(reverseStartingWith(str, 'h'));

輸出

以下是控制檯中的輸出 -

olleh world, woh are you

更新於:2020 年 9 月 16 日

181 次瀏覽

開始你的 事業

完成課程獲取認證

開始
廣告