Unicode Property Escapes cho phép khớp ký tự dựa trên thuộc tính Unicode của chúng (như chữ cái, số, emoji, ký tự điều khiển, v.v.) bằng cách sử dụng cờ u (unicode flag).
Cú pháp: \p{PropertyName} hoặc \P{PropertyName} (phủ định).
Ví dụ minh họa
Trích xuất tất cả emoji từ chuỗi văn bản:
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Unicode Property Escapes</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
.sample, .result { font-size: 20px; font-weight: 500; }
</style>
</head>
<body>
<h1>Trích xuất Emoji bằng Unicode Property Escapes</h1>
<div class="sample">Xin chào 😆😀 Thế giới 🙂😊</div>
<div style="color: green;" class="result"></div>
<button class="btn">NHẤN VÀO ĐÂY</button>
<h3> Nhấn nút để trích xuất emoji bằng regex </h3>
<script>
const sampleEle = document.querySelector(".sample").innerHTML;
const btnEle = document.querySelector(".btn");
const resEle = document.querySelector(".result");
// \p{Emoji_Presentation} khớp các ký tự hiển thị dưới dạng emoji
const emojiRegex = /\p{Emoji_Presentation}/gu;
btnEle.addEventListener("click", () => {
const matches = sampleEle.match(emojiRegex);
resEle.innerHTML = matches ? matches.join(" ") : "Không tìm thấy emoji";
});
</script>
</body>
</html>
Kết quả
Khi nhấn nút, các emoji 😆 😀 🙂 😊 sẽ được tách ra và hiển thị.
Một số thuộc tính Unicode hữu ích:
\p{L}hoặc\p{Letter}- mọi chữ cái\p{N}hoặc\p{Number}- mọi số\p{Script=Latin}- ký tự Latin\p{Script=Han}- ký tự Hán (Kanji/Hanzi)\p{Emoji}- tất cả emoji\p{White_Space}- khoảng trắng
Lưu ý: Luôn sử dụng cờ u (unicode) khi làm việc với Unicode property escapes.