เราจำเป็นต้องเขียนฟังก์ชัน 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