วิธีการ exec
วิธีการ exec ดำเนินการค้นหาใน
สตริงตาม นิพจน์ทั่วไปที่กำหนด ผลลัพธ์ที่ส่งคืนคือสตริงย่อย
ที่พบและกลุ่มจับของมัน นอกจากนี้
การเรียกใช้วิธีการนี้แต่ละครั้งต่อมา
จะเริ่มค้นหาจากตำแหน่ง
ที่สตริงย่อยที่พบครั้งก่อนสิ้นสุดลง
หากไม่พบการตรงกัน
จะส่งคืน null
ไวยากรณ์
นิพจน์_ทั่วไป.test(สตริง);
ตัวอย่าง
ลองตรวจสอบการทำงานของวิธีการ:
let str = '12 34 56';
let reg = /\d+/g;
let res1 = reg.exec(str);
console.log(res1);
let res2 = reg.exec(str);
console.log(res2);
let res3 = reg.exec(str);
console.log(res3);
let res4 = reg.exec(str);
console.log(res4);
ผลลัพธ์จากการดำเนินการโค้ด:
[12]
[34]
[56]
null
ตัวอย่าง
ลองใช้วิธีการในลูป:
let str = '12 34 56';
let reg = /\d+/g;
let res;
while (res = reg.exec(str)) {
console.log(res);
}
ผลลัพธ์จากการดำเนินการโค้ด:
[12]
[34]
[56]
ตัวอย่าง
การตรงกันที่พบสามารถแยกออก ตามกลุ่มจับได้:
let str = '12 34 56';
let reg = /(\d)(\d)/g;
let res;
while (res = reg.exec(str)) {
console.log(res);
}
ผลลัพธ์จากการดำเนินการโค้ด:
[12, 1, 2]
[34, 3, 4]
[56, 5, 6]
ตัวอย่าง
ด้วยคุณสมบัติ lastIndex
สามารถกำหนดตำแหน่งที่ควร
เริ่มค้นหา:
let str = '12 34 56';
let reg = /\d+/g;
reg.lastIndex = 2;
let res1 = reg.exec(str)
console.log(res1);
let res2 = reg.exec(str)
console.log(res2);
ผลลัพธ์จากการดำเนินการโค้ด:
[34]
[56]
ตัวอย่าง
ด้วยตัวปรับแต่ง y
สามารถตรึงตำแหน่ง
เริ่มต้นของการค้นหา:
let str = '12 34 56';
let reg = /\d+/y;
reg.lastIndex = 2;
let res1 = reg.exec(str)
console.log(res1);
let res2 = reg.exec(str)
console.log(res2);
ผลลัพธ์จากการดำเนินการโค้ด:
null
[12]