\w vs \W
\w khớp word character: chữ cái (a-z, A-Z), số (0-9), gạch dưới (_). \W khớp non-word character: khoảng trắng, dấu câu, ký tự đặc biệt.
Cú pháp
new RegExp("\\w", "g"); // hoặc /\w/g
new RegExp("\\W", "g"); // hoặc /\W/g
Ví dụ 1: \w - Word characters
<html> <body> <script> var str = "**Tutorix is the best e-learning platform%!"; var regpat = /\w/g; var result = str.match(regpat); document.write(result); </script> </body> </html>
Kết quả
T,u,t,o,r,i,x,i,s,t,h,e,b,e,s,t,e,l,e,a,r,n,i,n,g,p,l,a,t,f,o,r,m
Ví dụ 2: \W - Non-word characters
<html> <body> <script> var str = "**Tutorix is the best e-learning platform%!"; var regpat = /\W/g; var result = str.match(regpat); document.write(result); </script> </body> </html>
Kết quả
*,*, , , , ,-, ,%,!
Lưu ý: \w = [A-Za-z0-9_]. Không khớp tiếng Việt có dấu, ký tự Unicode khác. Dùng Unicode property escapes: /\p{L}/gu cho chữ cái mọi ngôn ngữ.