Reputation: 10913
I don't know why but Chrome dev tools regex test returning a different result everytime its called. I have this as the string to be tested:
SELECT tbl_school.id AS tbl_school_id, school, tbl_students.id AS tbl_students_id, name, hobby, school_id, course_id FROM tbl_school, tbl_students WHERE tbl_school.id = 's' dd
ORDER BY tbl_school.id ASC
The where regex is:
var where_regex = /where/ig
Here's a screenshot of the results, as you can see its changing everytime its called but I didn't change anything in the string. I'll really appreciate an explanation for this
Upvotes: 3
Views: 2575
Reputation: 106385
It's because of /g
flag AND the fact that the same regex object is used. Quoting the doc (MDN)
As with
exec
(or in combination with it),test
called multiple times on the same global regular expression instance will advance past the previous match.
Consider this:
var r = /w/g;
console.log( r.test('Awa') ); // true
console.log( r.test('Awa') ); // false
console.log( r.test('Awa') ); // true
console.log( r.test('Awa') ); // false
console.log( /w/ig.test('Awa') ); // true
console.log( /w/ig.test('Awa') ); // true
console.log( /w/ig.test('Awa') ); // true
console.log( /w/ig.test('Awa') ); // true
In the first group of statements (using the same regex object stored in r
variable) the second match starts from the place where the first one has finished (i.e., after w
). Note that using //g.test
after it has failed will reset it - so the match will start from the beginning of that line.
But in the second group of statements each time a new regex object is created, and each of these (obviously) stores the position of the last match separately. Hence, it's four true
there.
The bottom line is that it's quite... weird to use /g
with test
method - unless you want the pattern to walk over the string, of course. Remember, test
returns true
or false
(and doesn't capture anything), so in normal cases enabling the regex global mode is redundant, to say the least.
Upvotes: 5