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

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

ภาพรวม

บทความนี้สาธิตวิธีแทนที่อักขระพิเศษ (Non-alphanumeric) ในสตริงด้วย ASCII Code ของมัน

ตัวอย่าง

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

การนำไปใช้

const specialToASCII = (str) => {
  let res = '';
  for (let i = 0; i < str.length; i++) {
    const char = str[i];
    // ตรวจสอบ: เป็นตัวเลข, ตัวอักษร, หรือ Space
    if (+char || char.toLowerCase() !== char.toUpperCase() || char === ' ') {
      res += char;
      continue;
    }
    // Special Character -> ASCII Code
    res += char.charCodeAt(0);
  }
  return res;
};

console.log(specialToASCII('Th!s !s @ str!ng th@t cont@!ns some special characters!!'));

ผลลัพธ์

Th33s 33s 64 str33ng th64t cont6433ns some special characters3333

ปัญหาของโค้ดต้นฉบับ

  • Condition `+char` จะเป็น false สำหรับ '0' (เพราะ +'0' === 0 -> falsy)
  • ตัวเลข '0' จะถูกแปลงเป็น ASCII 48 ผิดพลาด

วิธีที่ถูกต้องและทันสมัย

const specialToASCIIFixed = (str) => 
  [...str].map(c => 
    /[a-zA-Z0-9 ]/.test(c) ? c : c.charCodeAt(0)
  ).join('');

// หรือกำหนด Charset ที่อนุญาตชัดเจน
const specialToASCIIExplicit = (str, allowed = /^[a-zA-Z0-9 ]$/) => 
  [...str].map(c => allowed.test(c) ? c : c.charCodeAt(0)).join('');

การขยาย: Unicode Code Points

const toCodePoints = (str) => 
  [...str].map(c => c.codePointAt(0).toString(16).toUpperCase().padStart(4, '0'))
    .join(' ');

console.log(toCodePoints('Hello 😀')); // 0048 0065 006C 006C 006F 0020 1F600

การประยุกต์ใช้

  • Data Sanitization: Escape Special Characters
  • Debugging: Visualize Invisible Characters
  • Encoding/Decoding Pipelines
  • Security: Detect Hidden Characters

ข้อควรระวัง

  • ASCII vs Unicode: charCodeAt() ให้ UTF-16 Code Unit, codePointAt() ให้ Unicode Code Point
  • Surrogate Pairs: Emoji ใช้ 2 Code Units
  • Performance: String Concatenation ใน Loop ช้า -> ใช้ Array.join()