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

ค้นหาตัวอักษร Word Character ใน String ด้วย JavaScript RegExp (\w)

ใน JavaScript Regular Expression \w (Word Character) ใช้จับคู่ ตัวอักษรภาษาอังกฤษ (a-z, A-Z), ตัวเลข (0-9), และ Underscore (_) เทียบเท่ากับ [a-zA-Z0-9_]

Syntax

/\w/        // จับคู่ Word Character ตัวแรก
/\w/g       // จับคู่ Word Character ทั้งหมด (Global flag)
/\w+/       // จับคู่ Word Character ติดกัน 1 ตัวขึ้นไป (Word)

ตัวอย่าง: หา Word Character ทั้งหมดใน String

const myStr = "100% Responsive!";
const reg = /\w/g;
const matches = myStr.match(reg);
console.log(matches); // ["1", "0", "0", "R", "e", "s", "p", "o", "n", "s", "i", "v", "e"]

คำอธิบาย: % และ ! และ Space ไม่ใช่ Word Character จึงไม่ถูกจับคู่

ตัวอย่าง: ดึง "คำ" (Word) ทั้งหมดด้วย \w+

const text = "Hello world! This is JavaScript_123.";
const words = text.match(/\w+/g);
console.log(words); // ["Hello", "world", "This", "is", "JavaScript_123"]

ตัวอย่าง: แทนที่ Non-Word Character ด้วย \W (Inverse)

// \W = [^\w] = ไม่ใช่ Word Character
const cleaned = "Hello! @World#".replace(/\W/g, '_');
console.log(cleaned); // "Hello___World_"

⚠️ ข้อจำกัดสำคัญ: Unicode / ภาษาไทย

\w ใน JavaScript (ECMAScript 2018 ก่อนหน้า) รองรับเฉพาะ ASCII เท่านั้น (a-z, A-Z, 0-9, _)

  • ไม่จับคู่ ตัวอักษรไทย, อารบิก, จีน, อีโมจิ, อักขระ Unicode อื่นๆ
  • ตัวอย่าง: /\w/.test("ไทย") → false

แก้ไข: ใช้ Unicode Flag u (ES2018+)

// ใช้ Unicode Property Escape \p{L} (Letter) และ \p{N} (Number)
const unicodeWord = /[\p{L}\p{N}_]/gu; // ต้องใช้ [] รวม _ เอง

const thai = "สวัสดี123_世界";
console.log(thai.match(unicodeWord)); // ["ส", "ว", "ส", "ด", "ี", "1", "2", "3", "_", "世", "界"]

// หรือจับคู่ "คำ" แบบ Unicode
const unicodeWords = thai.match(/[\p{L}\p{N}_]+/gu);
console.log(unicodeWords); // ["สวัสดี123_", "世界"]

ตารางสรุป

PatternความหมายASCII Only?Unicode (u flag)?
\w[a-zA-Z0-9_]✅ ใช่❌ ไม่ (ต้องใช้ \p{L}\p{N}_)
\W[^a-zA-Z0-9_]✅ ใช่❌ ไม่
[\p{L}\p{N}_]Unicode Letter + Number + _❌✅ ใช่ (ต้องใช้ u flag)

สรุป

  • \w = Word Character (ASCII: a-z, A-Z, 0-9, _)
  • ใช้ /\w+/g ดึงคำภาษาอังกฤษ/ตัวเลข/Underscore
  • สำหรับภาษาไทย/Unicode ต้องใช้ /\p{L}\p{N}_/gu แทน
  • ใช้ \W สำหรับจับคู่ Non-Word Character