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:
- let s value of tostring(string).
- let length length of s.
- let lastindex value of lastindex property.
- let value of tointeger(lastindex).
- if global property false, let = 0.
- if < 0 or > length set lastindex 0 , return null.
- call [[match]], giving arguments s , i. if [[match]] returned failure, go step 8; otherwise let r state result , go step 10.
- let = i+1.
- go step 6.
- let e r's endindex value.
- if global property true, set lastindex e.
- let n length of r's captures array. (this same value 15.10.2.1's ncapturingparens.)
- 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
Post a Comment