- test(): Kiểm tra khớp, trả về
boolean. Dùng cho điều kiệnif. - exec(): Trả về mảng chứa toàn bộ chuỗi khớp + các capture group + index + input. Dùng khi cần trích xuất dữ liệu.
Ví dụ
console.log(/^([a-z]+) ([A-Z]+)$/.exec("hello WORLD"));
console.log(/^([a-z]+) ([A-Z]+)$/.test("hello WORLD"));
Kết quả
[ 'hello WORLD', 'hello', 'WORLD', index: 0, input: 'hello WORLD', groups: undefined ] true
Giải thích: Phần tử đầu mảng exec là chuỗi khớp toàn bộ, các phần tử sau là capture group.