使用 JavaScript 移動母音和子音


問題

我們需要編寫一個 JavaScript 函式,它接受一個英語字母的字串。我們的函式構建一個新字串,每個子音應透過字母表向前推進 9 個位置。如果經過“z”,則從“a”重新開始。每個母音應向前推進 5 個位置。

示例

以下程式碼 −

 Live Demo

const str = 'sample string';
const moveWords = (str = '') => {
   str = str.toLowerCase();
   const legend = 'abcdefghijklmnopqrstuvwxyz';
   const isVowel = char => 'aeiou'.includes(char);
   const isAlpha = char => legend.includes(char);
   let res = '';
   for(let i = 0; i < str.length; i++){
      const el = str[i];
      if(!isAlpha(el)){
         res += el;
         continue;
      };
      let pos;
      const ind = legend.indexOf(el);
      if(isVowel(el)){
         pos = (21 + ind) % 26;
      }else{
         pos = (ind + 9) % 26;
      };
      res += legend[pos];
   };
   return res;
};
console.log(moveWords(str));

輸出

bvvyuz bcadwp

更新於: 17-4-2021

205 人次瀏覽

開啟你的 職業生涯

完成課程,獲得認證

開始學習
廣告
© . All rights reserved.