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

การแทนที่อักขระพิเศษด้วยค่า ASCII - JavaScript

แทนที่อักขระพิเศษ (non-alphanumeric, non-space) ในสตริงด้วยรหัส ASCII ของมัน

ตัวอย่าง

Input: 'Th!s !s @ str!ng th@t cont@!ns some special characters!!'
Output: 'Th33s 33s 64 str33ng th64t cont6433ns some special characters3333'

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

const str = 'Th!s !s @ str!ng th@t cont@!ns some special characters!!';

const specialToASCII = str => {
  let res = '';
  for (let i = 0; i < str.length; i++) {
    const ch = str[i];
    // ตัวเลข, ตัวอักษร, ช่องว่าง → คงเดิม
    if (+ch || ch.toLowerCase() !== ch.toUpperCase() || ch === ' ') {
      res += ch;
      continue;
    }
    // อักขระพิเศษ → ASCII code
    res += ch.charCodeAt(0);
  }
  return res;
};

console.log(specialToASCII(str));

ตรรกะการตรวจสอบ

  • +ch truthy → ตัวเลข 1-9 (0 จะ falsy → bug)
  • toLowerCase() !== toUpperCase() → ตัวอักษร (มี case)
  • ch === ' ' → ช่องว่าง
  • อื่นๆ → อักขระพิเศษ → charCodeAt(0)

ผลลัพธ์

Th33s 33s 64 str33ng th64t cont6433ns some special characters3333

บั๊ก: ตัวเลข 0 จะถูกแปลงเป็น ASCII 48 ควรเพิ่ม ch === '0' ในเงื่อนไข