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

ความแตกต่างระหว่าง test() และ exec() ใน JavaScript

test ทดสอบการจับคู่และคืนค่า boolean ส่วน exec จับกลุ่ม (capture groups) และจับคู่ regex กับ input

หากต้องการทดสอบ input string ว่าจับคู่กับ regular expression หรือไม่ RegExp.test เหมาะสมที่สุด จะคืนค่า boolean เหมาะสำหรับเงื่อนไข

RegExp.exec คืนค่า array-like พร้อม capture groups และ matched indexes ทั้งหมด เหมาะเมื่อต้องการทำงานกับกลุ่มที่จับได้หรือ indexes หลังจับคู่

ตัวอย่าง

console.log(/^([a-z]+) ([A-Z]+)$/.exec("hello WORLD")) console.log(/^([a-z]+) ([A-Z]+)$/.test("hello WORLD"))

ผลลัพธ์

[ 'hello WORLD',    'hello',    'WORLD',    index: 0,    input: 'hello WORLD',    groups: undefined ] true

หมายเหตุ: index แรกใน array ที่ exec คืนคือ string ที่จับคู่ทั้งหมด index ต่อไปคือกลุ่มแต่ละกลุ่มที่ regex จับได้