Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การใช้งานเมธอด exec() ของ Regex ใน JavaScript

exec()

exec() เป็น regex method ค้นหารูปแบบในสตริง คืนค่าออบเจ็กต์ของข้อความที่เจอ (มี index, input) หาไม่เจอคืน null แตกต่างจาก test() ที่คืน true/false

ตัวอย่างที่ 1: ค้นหา "est"

<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>

ผลลัพธ์

The object is est and its position is 16

ตัวอย่างที่ 2: ค้นหา "x"

<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>

ผลลัพธ์

The object is x and its position is 6