Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Công dụng của phương thức regex exec() trong JavaScript


exec()

exec() là phương thức regex. Tìm kiếm chuỗi theo mẫu (pattern) và, khác với test(), trả về văn bản tìm thấy dưới dạng đối tượng (object). Nếu không khớp trả về null.

Ví dụ 1

Kiểm tra mẫu "est" qua exec(). Sau khi duyệt, trả về mẫu dưới dạng object.

<html> <body> <script> 
    var obj = /est/.exec("Tutorix is the best e-learning platform"); 
    document.write("The object is " + obj[0] + " and its position is " + obj.index); 
</script> </body> </html>

Kết quả

The object is est and its position is 16

Ví dụ 2

Kiểm tra mẫu "x" qua exec().

<html> <body> <script> 
    var obj = /x/.exec("Tutorix is the best e-learning platform"); 
    document.write("The object is " + obj[0] + " and its position is " + obj.index); 
</script> </body> </html>

Kết quả

The object is x and its position is 6