Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

แทนที่ตัวอักษรด้วยตัวอักษรถัดไป n ตำแหน่ง - JavaScript

สตริง: 'abcd' เลข n: 2 → ผลลัพธ์: 'cdef' (Caesar cipher)

ตัวอย่างโค้ด

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

คำอธิบาย: หาตำแหน่งใน alphabet string บวก n ใช้ modulo 26 (alphabet.length) วนรอบ z→a สมมติ input เป็น lowercase เท่านั้น

ขยาย: รองรับ uppercase, non-alphabet chars, negative n สำหรับถอยหลัง