Why does JavaScript RegExp maintain state between calls?

Today I came across a very strange problem with regular expression JavaScript. When using the global modifier (// g), RegExp.test () gives different values ​​in subsequent calls. Can someone explain why?

var s = "youtube.com/watch?v=XyeebVA3DNk"; var re1 = /^youtube\.com\/watch[a-zA-Z0-9_\-\?\&\=\/]+/g; console.log(re1.test(s)); // true console.log(re1.test(s)); // false console.log(re1.test(s)); // true console.log(re1.test(s)); // false console.log(re1.test(s)); // true console.log(re1.test(s)); // false console.log(re1.test(s)); // true var re2 = /^youtube\.com\/watch[a-zA-Z0-9_\-\?\&\=\/]+/; console.log(re2.test(s)); // true console.log(re2.test(s)); // true console.log(re2.test(s)); // true console.log(re2.test(s)); // true console.log(re2.test(s)); // true console.log(re2.test(s)); // true 

I can reproduce this in Chrome 8 and FireFox 3.6.

+6
javascript regex
source share
2 answers

This is only when using the g flag. I agree that this is not the best design, but you need to allow you to scroll through the matches, for example. with re1.exec .

 var s = "fo1,fo2,fo3,"; var re1 = /fo\d,/g; var match; while(match = re1.exec(s)) { alert(match); } 
+8
source share

"If your regular expression uses the g flag, you can use the exec method several times to find consecutive matches on the same line. When you do this, the search starts with the substring s specified by the regular expression of the lastIndex property (the test will also support the property lastIndex).

"As with exec (or in conjunction with it), a test called multiple times in the same instance of a global regular expression will pass by the previous match."

 var s = "youtube.com/watch?v=XyeebVA3DNk"; var re1 = /^youtube\.com\/watch[a-zA-Z0-9_\-\?\&\=\/]+/g; console.log(re1.test(s)); // true var re1 = /^youtube\.com\/watch[a-zA-Z0-9_\-\?\&\=\/]+/g; console.log(re1.test(s)); // true 
+2
source share

All Articles