CodingForums.com

CodingForums.com (http://www.codingforums.com/index.php)
-   JavaScript programming (http://www.codingforums.com/forumdisplay.php?f=2)
-   -   regex test problem (http://www.codingforums.com/showthread.php?t=283840)

BubikolRamios 12-09-2012 08:35 AM

regex test problem
 
How do you explain that ?

Code:

regexPattern = new RegExp("a","gi");
s = "a";
        alert (regexPattern.test(s));//--> true
        alert (regexPattern.test(s));//--> false
        alert (regexPattern.test(s));//--> true
        alert (regexPattern.test(s));//--> false
        //......

EDIT: if I modify each alert:
Code:

alert (regexPattern.test(s) + s.match(regexPattern));
obviously result of
Code:

s.match(regexPattern)
is the same on each alert.

Philip M 12-09-2012 10:54 AM

Hmm. Very odd! You seem to have exposed a bug (not a flower! :D) in the Javascript regex engine. Same in IE and Chrome.

Code:

var s = "a";
alert (/a/gi.test(s)); // true
alert (/a/gi.test(s)); // true
alert (/a/gi.test(s)); // true
alert (/a/gi.test(s)); // true


"If you make it idiot proof, they'll build a better idiot"

BubikolRamios 12-09-2012 11:12 AM

Quote:

Found a flower or bug
Bugs also there (-:

Yeah, tested the thing in chrome, before submiting here.
Not to mention hours lost, before 'lamp' turned on: "Damn, there something smell bad about .test".
I had .test in a loop and "a" string has been changing and on every second loop bad result.

AndrewGSW 12-09-2012 11:14 AM

Quote:

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.
Mozilla
Code:

regexPattern = new RegExp("a","gi");
s = "a";
        alert (regexPattern.test(s));//--> true
        alert(regexPattern.lastIndex); // 1
        alert (regexPattern.test(s));//--> false
        alert(regexPattern.lastIndex); // 0
        alert (regexPattern.test(s));//--> true
        alert(regexPattern.lastIndex); // 1
        alert (regexPattern.test(s));//--> false
        alert(regexPattern.lastIndex); // 0


AndrewGSW 12-09-2012 11:25 AM

If you remove the "g" global modifier - which is not relevant to test() - then it behaves as expected.

Added: I won't have JavaScript besmirched :D
(only joshing!)

Philip M 12-09-2012 11:28 AM

Quote:

Originally Posted by AndrewGSW (Post 1298480)
If you remove the "g" global modifier - which is not relevant to test() - then it behaves as expected.

You are right! Woot! :)
We learn something every day. Sometimes something worth knowing!

007julien 12-09-2012 12:17 PM

It is the same thing with prompt or confirm and if an "a" take place of s !

In short (See this MDN page *) you have to restore the regexPattern.lastIndex to 0 before each new test !

Good to know. Thanks !

(*) Or better ECMAScript Language Specification 15.10.6.2 and 15.10.6.3


All times are GMT +1. The time now is 11:34 AM.

Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.