javascript - Why does a RegExp with global flag give wrong results? -


what problem regular expression when use global flag , case insensitive flag? query user generated input. result should [true, true].

var query = 'foo b'; var re = new regexp(query, 'gi'); var result = []; result.push(re.test('foo bar')); result.push(re.test('foo bar')); // result [true, false] 

var reg = /^a$/g;  for(i = 0; i++ < 10;)     console.log(reg.test("a"));

the regexp object keeps track of lastindex match occurred, on subsequent matches start last used index, instead of 0. take look:

var query = 'foo b'; var re = new regexp(query, 'gi'); var result = []; result.push(re.test('foo bar'));  alert(re.lastindex);  result.push(re.test('foo bar')); 

if don't want manually reset lastindex 0 after every test, remove g flag.

here's algorithm specs dictate (section 15.10.6.2):

regexp.prototype.exec(string)

performs regular expression match of string against regular expression , returns array object containing results of match, or null if string did not match string tostring(string) searched occurrence of regular expression pattern follows:

  1. let s value of tostring(string).
  2. let length length of s.
  3. let lastindex value of lastindex property.
  4. let value of tointeger(lastindex).
  5. if global property false, let = 0.
  6. if < 0 or > length set lastindex 0 , return null.
  7. call [[match]], giving arguments s , i. if [[match]] returned failure, go step 8; otherwise let r state result , go step 10.
  8. let = i+1.
  9. go step 6.
  10. let e r's endindex value.
  11. if global property true, set lastindex e.
  12. let n length of r's captures array. (this same value 15.10.2.1's ncapturingparens.)
  13. return new array following properties:
    • the index property set position of matched substring within complete string s.
    • the input property set s.
    • the length property set n + 1.
    • the 0 property set matched substring (i.e. portion of s between offset inclusive , offset e exclusive).
    • for each integer such > 0 , ≤ n, set property named tostring(i) ith element of r's captures array.

Comments

Popular posts from this blog

How has firefox/gecko HTML+CSS rendering changed in version 38? -

javascript - Complex json ng-repeat -

jquery - Cloning of rows and columns from the old table into the new with colSpan and rowSpan -