Unicode Property Escapes ช่วยให้จับคู่อักขระได้โดยอิงจากคุณสมบัติ Unicode โดยใช้ flag u ทำให้จัดการอีโมจิ อักขระพิเศษ และภาษาต่างๆ ได้ง่ายขึ้น
ตัวอย่าง
ตัวอย่างการดึงเฉพาะอีโมจิจากข้อความ:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Unicode Property Escapes Example</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
.sample, .result { font-size: 20px; font-weight: 500; }
</style>
</head>
<body>
<h1>Unicode Property Escapes JavaScript Regular Expressions</h1>
<div class="sample">Hello 😆😀 World 🙂😊</div>
<div style="color: green;" class="result"></div>
<button class="btn">CLICK HERE</button>
<h3> Click on the above button to extract the emojis using regex </h3>
<script>
let sampleEle = document.querySelector(".sample").innerHTML;
let btnEle = document.querySelector(".btn");
let resEle = document.querySelector(".result");
const EmojiRegEx = /\p{Emoji_Presentation}/gu;
btnEle.addEventListener("click", () => {
const matches = sampleEle.match(EmojiRegEx);
resEle.innerHTML = matches ? matches.join(" ") : "No emojis found";
});
</script>
</body>
</html>
คำอธิบาย
- /\p{Emoji_Presentation}/gu: ใช้ Unicode property
Emoji_Presentationกับ flagu(unicode) และg(global) - คุณสมบัติ Unicode อื่นๆ ที่น่าสนใจ:
\p{L}(ตัวอักษร),\p{N}(ตัวเลข),\p{Script=Thai}(อักษรไทย) - Flag
uจำเป็นต้องใช้เสมอเมื่อใช้ Unicode property escapes
ผลลัพธ์
ก่อนกดปุ่ม: "Hello 😆😀 World 🙂😊" | หลังกดปุ่ม: แสดงเฉพาะอีโมจิ "😆 😀 🙂 😊"