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

Regular Expression ลบอักขระพิเศษทั้งหมดจากสตริง JavaScript

ใช้ Regex /[^\w\s]/gi กับ replace() เพื่อลบอักขระพิเศษทั้งหมด (เก็บแค่ตัวอักษร ตัวเลข Underscore และ Whitespace)

ตัวอย่าง

<html>
  <head>
    <script>
      var str = "@!Welcome to our website$$";
      document.write(str);
      // ลบอักขระพิเศษทั้งหมด
      document.write("<br>" + str.replace(/[^\w\s]/gi, ''));
    </script>
  </head>
  <body>
  </body>
</html>

อธิบาย Regex: /[^\w\s]/gi

ส่วนความหมาย
[^...]Negated Character Class (ไม่ใช่ตัวอักษรในชุดนี้)
\wWord characters: [a-zA-Z0-9_]
\sWhitespace: space, tab, newline, ฯลฯ
giGlobal + Case-Insensitive

ผลลัพธ์

@!Welcome to our website$$
Welcome to our website

กรณีพิเศษและปรับแต่ง

// 1. เก็บแค่ภาษาอังกฤษ ตัวเลข (ไม่เก็บ underscore, ไทย, whitespace)
str.replace(/[^a-zA-Z0-9]/g, '');

// 2. เก็บภาษาไทย ด้วย (Unicode property - ES2018)
str.replace(/[^\p{L}\p{N}\s]/gu, ''); // \p{L}=Letter, \p{N}=Number

// 3. เก็บเฉพาะตัวอักษร (ไม่เก็บตัวเลข underscore)
str.replace(/[^a-zA-Z\s]/g, '');

// 4. ลบเฉพาะสัญลักษณ์เฉพาะเจาะจง
str.replace(/[!@#$%^&*()]/g, '');

หมายเหตุ: \w รวม Underscore (_) และตัวเลข ถ้าต้องการแค่ตัวอักษร ต้องปรับ Regex เอง