exec metodi
exec metodi
berilgan oddiy ifoda bo‘yicha satr bo‘yida qidiruvni amalga oshiradi. Natijada topilgan
qatorsatr va uning "karmalari" (capturing groups) qaytariladi. Har bir
keyingi ushbu metod chaqiruvi
qidiruvni oldingi
topilgan qatorsatr tugagan joydan
boshlaydi. Agar moslik
topilmasa - null qaytariladi.
Sintaksis
javascriptoddiy_ifoda.test(satr);
Misol
Metodning ishlashini tekshiramiz:
javascriptlet 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);
Kodni bajarish natijasi:
javascript[12]
[34]
[56]
null
Misol
Metoddan tsiklda foydalanamiz:
javascriptlet str = '12 34 56';
let reg = /\d+/g;
let res;
while (res = reg.exec(str)) {
console.log(res);
}
Kodni bajarish natijasi:
javascript[12]
[34]
[56]
Misol
Topilgan mosliklarni "karmalar" (capturing groups) bo‘yicha ajratish mumkin:
javascriptlet str = '12 34 56';
let reg = /(\d)(\d)/g;
let res;
while (res = reg.exec(str)) {
console.log(res);
}
Kodni bajarish natijasi:
javascript[12, 1, 2]
[34, 3, 4]
[56, 5, 6]
Misol
lastIndex xususiyati yordamida
qidiruv boshlanishi kerak bo‘lgan
o‘rni belgilash mumkin:
javascriptlet 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);
Kodni bajarish natijasi:
javascript[34]
[56]
Misol
y modifikatori yordamida
qidiruv boshlanish o‘rnini
belgilab qo‘yish mumkin:
javascriptlet 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);
Kodni bajarish natijasi:
javascriptnull
[12]