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

เข้ารหัสสตริงใน JavaScript

เราต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงเป็นอาร์กิวเมนต์แรก และตัวเลขเป็นอาร์กิวเมนต์ที่สอง ฟังก์ชันควรแทนที่ตัวอักษรแต่ละตัวของสตริงโดยเลื่อนมันขึ้นในลำดับอักษรตามตัวเลขที่ให้มา การเลื่อนควรวนกลับไปที่จุดเริ่มต้นหรือจุดสิ้นสุดของอักษร เช่น a ควรตาม z แทนที่จะเป็น undefined หรือผลลัพธ์ว่างเปล่า

ตัวอย่าง

const str = 'this is a str';
const encryptString = (str = '', num = 1) => {
  const alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
  str = str.toLowerCase();
  let res = "";
  for (let i = 0; i < str.length; i++) {
    const letter = str[i];
    if (alphabet.indexOf(letter) === -1) {
      res += letter;
      continue;
    }
    let index = alphabet.indexOf(letter) + num % 26;
    if (index > 25){
      index -= 26;
    };
    if (index < 0){
      index += 26;
    };
    if(str[i] === str[i].toUpperCase()){
      res += alphabet[index].toUpperCase();
    }else{
      res += alphabet[index];
    };
  }
  return res;
};
console.log(encryptString(str, 4));

ผลลัพธ์

ผลลัพธ์ในคอนโซลจะเป็นดังนี้:

xlmw mw e wxv