Computer >> 컴퓨터 >  >> 프로그램 작성 >> JavaScript

JavaScript에서 주어진 문자열 N의 각 문자를 알파벳 아래로 이동하는 방법은 무엇입니까?

<시간/>

우리에게는 일련의 알파벳이 주어집니다. 우리의 임무는 각 알파벳을 영어 알파벳에서 n 알파벳만큼 떨어진 알파벳으로 바꾸는 것입니다.

n =1인 경우 b로 교체하고 b를 c로 교체하는 등(z는 a로 교체됨)

예:

const str = "crazy";
const n = 1;

출력은 -

여야 합니다.
alphabeticShift(inputString) = "dsbaz".

예시

다음은 코드입니다 -

const str = 'crazy';
const alphabeticShift = (str = '', n = 1) => {
   let arr = [];
   for(let i = 0; i < str.length; i++) {
      arr.push(String.fromCharCode((str[i].charCodeAt() + n)));
   }
   let res = arr.join("").replace(/{/g, 'a');;
   return res;
};
console.log(alphabeticShift(str));

출력

다음은 콘솔의 출력입니다 -

dsbaz