Metoda exec
Metoda exec kryen kërkime në
një string duke përdorur një shprehje të rregullt të dhënë. Rezultati kthen nënstringun e gjetur
dhe grupet e tij (capturing groups). Në të njëjtën kohë, çdo
thirrje pasuese e kësaj metode
do të fillojë kërkimin nga vendi
ku përfundoi nënstringu i gjetur i mëparshëm.
Nëse nuk gjendet një përputhje
kthehet null.
Sintaksa
shprehja_jo_rregullte.exec(string);
Shembull
Le të kontrollojmë funksionimin e metodës:
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);
Rezultati i ekzekutimit të kodit:
[12]
[34]
[56]
null
Shembull
Le të përdorim metodën në një cikël:
let str = '12 34 56';
let reg = /\d+/g;
let res;
while (res = reg.exec(str)) {
console.log(res);
}
Rezultati i ekzekutimit të kodit:
[12]
[34]
[56]
Shembull
Përputhjet e gjetura mund të shpërndahen në grupe (capturing groups):
let str = '12 34 56';
let reg = /(\d)(\d)/g;
let res;
while (res = reg.exec(str)) {
console.log(res);
}
Rezultati i ekzekutimit të kodit:
[12, 1, 2]
[34, 3, 4]
[56, 5, 6]
Shembull
Duke përdorur vetinë lastIndex
mund të vendosni pozitën nga e cila duhet
të fillojë kërkimi:
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);
Rezultati i ekzekutimit të kodit:
[34]
[56]
Shembull
Duke përdorur modifikuesin y
mund të fiksoni pozitën
e fillimit të kërkimit:
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);
Rezultati i ekzekutimit të kodit:
null
[12]