ใช้ Regular Expression กับเมธอด replace() เพื่อลบข้อความที่อยู่ระหว่างสองส่วนที่กำหนด (เช่น ข้อความในวงเล็บ)
ตัวอย่าง: ลบข้อความในวงเล็บ
<html>
<head>
<script>
var str = "Welcome to Qries (website)";
document.write(str);
// ลบข้อความในวงเล็บ รวมวงเล็บด้วย
document.write("<br>" + str.replace(/ *\([^)]*\) */g, ""));
</script>
</head>
<body>
</body>
</html>
ผลลัพธ์
Welcome to Qries (website) Welcome to Qries
อธิบาย Regex: / *\([^)]*\) */g
| ส่วน | ความหมาย |
|---|---|
* | Space 0 หรือมากกว่า (ก่อนวงเล็บ) |
\( | วงเล็บเปิด (escape ด้วย \) |
[^)]* | ตัวอักษรใดๆ ที่ไม่ใช่วงเล็บปิด 0 หรือมากกว่า |
\) | วงเล็บปิด |
* | Space 0 หรือมากกว่า (หลังวงเล็บ) |
g | Global flag (ลบทุกครั้งที่เจอ) |
ตัวอย่างเพิ่มเติม
// ลบ HTML tags "<p>Hello</p>".replace(/<[^>]*>/g, ""); // "Hello" // ลบคอมเมนต์ CSS /* ... */ "color: red; /* comment */".replace(/\/\*[\s\S]*?\*\//g, ""); // "color: red; " // ลบระหว่างเครื่องหมายคูณ * "a*b*c".replace(/\*[^*]*/g, ""); // "ac" // Named groups (ES2018) - อ่านง่ายขึ้น const regex = /(?\()(? [^)]*)(? \))/; "text (remove me)".replace(regex, ""); // "text "
หมายเหตุ: Regex นี้ไม่รองรับ Nested Parentheses (วงเล็บซ้อน) สำหรับกรณีซับซ้อนควรใช้ Parser จริง