在 JavaScript 中用第 n 位後一個字母替換字母


我們需要編寫一個 JavaScript 函式,它取一個字母字串和一個數字(比如 n)。然後我們應該返回一個新字串,其中所有字元都替換為相鄰字母表中第 n 個字母之後相應的字母。

例如,如果字串和數字為 −

const str = 'abcd';
const n = 2;

那麼輸出應該是 −

const output = 'cdef';

示例

程式碼如下 −

const str = 'abcd';
const n = 2;
const replaceNth = (str, n) => {
   const alphabet = 'abcdefghijklmnopqrstuvwxyz';
   let i, pos, res = '';
   for(i = 0; i < str.length; i++){
      pos = alphabet.indexOf(str[i]);
      res += alphabet[(pos + n) % alphabet.length];
   };
   return res;
};
console.log(replaceNth(str, n));

輸出

控制檯中的輸出將是 −

cdef

更新於: 20-11-2020

401 次瀏覽

開啟您的 職業生涯

完成課程即可拿到證書

開始
廣告
© . All rights reserved.