Visit Mozilla.org

Talk:Core JavaScript 1.5 Reference:Global Objects:RegExp:test

From MDC


str = 'foobar';
pattern = "foo";
re = new RegExp(pattern, 'g');

alert(re.test(str)); // true
alert(re.test(str)); //false

//why does it equate to false the 2nd time?
RegExps with the /g flag are meant for iterating through a string, and they contain a lastIndex property which tracks the current location within the string. In this case, it matches the first time, but the second time lastIndex is large enough that /foo/ doesn't match "bar" (I think -- I haven't checked exact details), so it returns false.
By the way, commenting here with questions isn't the ideal location because it's not likely to be seen by the right people -- the mozilla.dev.tech.javascript newsgroup is a better place to ask questions.  :-) --Waldo 16:06, 6 March 2007 (PST)