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

javascriptshprehja_jo_rregullte.exec(string);

Shembull

Le të kontrollojmë funksionimin e metodës:

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);

Rezultati i ekzekutimit të kodit:

javascript[12]
[34]
[56]
null

Shembull

Le të përdorim metodën në një cikël:

javascriptlet str = '12 34 56';
let reg = /\d+/g;

let res;
while (res = reg.exec(str)) {
  console.log(res);
}

Rezultati i ekzekutimit të kodit:

javascript[12]
[34]
[56] 

Shembull

Përputhjet e gjetura mund të shpërndahen në grupe (capturing groups):

javascriptlet str = '12 34 56';
let reg = /(\d)(\d)/g;

let res;
while (res = reg.exec(str)) {
  console.log(res);
}

Rezultati i ekzekutimit të kodit:

javascript[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:

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);

Rezultati i ekzekutimit të kodit:

javascript[34]
[56]

Shembull

Duke përdorur modifikuesin y mund të fiksoni pozitën e fillimit të kërkimit:

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);

Rezultati i ekzekutimit të kodit:

javascriptnull
[12]

Shihni gjithashtu

  • metoda test,
    e cila kontrollon një string
  • metoda match,
    e cila kërkon përputhje në një string
  • metoda matchAll,
    e cila kërkon të gjitha përputhjet në një string
  • metoda replace,
    e cila kryen kërkim dhe zëvendësim
  • metoda search,
    e cila kryen kërkim
  • metoda split,
    e cila ndan një string