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

การเลื่อนตำแหน่งสระและพยัญชนะใน JavaScript


ปัญหา

เราต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงของตัวอักษรภาษาอังกฤษ ฟังก์ชันควรสร้างสตริงใหม่ โดยพยัญชนะแต่ละตัวถูกเลื่อนไปข้างหน้า 9 ตำแหน่งในอักษรอังกฤษ หากเกิน 'z' ให้เริ่มที่ 'a' ใหม่ ส่วนสระแต่ละตัวถูกเลื่อน 5 ตำแหน่ง

ตัวอย่าง

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

const str = 'sample string';
const moveWords = (str = '') => {
  str = str.toLowerCase();
  const legend = 'abcdefghijklmnopqrstuvwxyz';
  const isVowel = char => 'aeiou'.includes(char);
  const isAlpha = char => legend.includes(char);
  let res = '';
  for(let i = 0; i < str.length; i++){
    const el = str[i];
    if(!isAlpha(el)){
      res += el;
      continue;
    };
    let pos;
    const ind = legend.indexOf(el);
    if(isVowel(el)){
      pos = (21 + ind) % 26;
    }else{
      pos = (ind + 9) % 26;
    };
    res += legend[pos];
  };
  return res;
};
console.log(moveWords(str));

ผลลัพธ์

bvvyuz bcadwp