Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Javascript

จะเปลี่ยนตัวอักษรแต่ละตัวในสตริงที่กำหนด N ลงในตัวอักษรใน JavaScript ได้อย่างไร?


เราได้รับชุดตัวอักษร งานของเราคือแทนที่ตัวอักษรแต่ละตัวด้วยตัวอักษรที่ไม่ใช่ตัวอักษรภาษาอังกฤษ n ตัว

กล่าวคือ

ถ้า n =1 ให้แทนที่ a ด้วย 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