exec Metodu
exec metodu, bir dize üzerinde belirli bir düzenli ifadeye göre arama yapar. Sonuç olarak bulunan alt dize ve onun grupları (capturing groups) döndürülür. Ayrıca, bu metodun her bir sonraki çağrısı, bir önceki bulunan alt dizenin bittiği yerden aramaya başlayacaktır. Eğer eşleşme bulunamazsa - null döndürülür.
Sözdizimi
duzenli_ifade.exec(dize);
Örnek
Metodun çalışmasını kontrol edelim:
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);
Kodun çalıştırılmasının sonucu:
[12]
[34]
[56]
null
Örnek
Metodu bir döngü içinde kullanalım:
let str = '12 34 56';
let reg = /\d+/g;
let res;
while (res = reg.exec(str)) {
console.log(res);
}
Kodun çalıştırılmasının sonucu:
[12]
[34]
[56]
Örnek
Bulunan eşleşmeler gruplara ayrılabilir:
let str = '12 34 56';
let reg = /(\d)(\d)/g;
let res;
while (res = reg.exec(str)) {
console.log(res);
}
Kodun çalıştırılmasının sonucu:
[12, 1, 2]
[34, 3, 4]
[56, 5, 6]
Örnek
lastIndex özelliği kullanılarak
aranmaya başlanacak konum belirlenebilir:
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);
Kodun çalıştırılmasının sonucu:
[34]
[56]
Örnek
y değiştiricisi kullanılarak
arama başlangıç konumu sabitlenebilir:
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);
Kodun çalıştırılmasının sonucu:
null
[12]