Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Regex with .test()

> var p = /abc/gi;
> var s = "abc";
> p.test(s);
  true
> p.test(s);
  false;

When I run this code on console of Chrome I Have this output above. Each time I call '.test()' I get a diferent value. Someone could explain to me why this happens? thanks

like image 324
Felipe Couto Avatar asked Oct 05 '11 11:10

Felipe Couto


1 Answers

The behavior is due to the "g" modifier, i.e. matches three times, no match the fourth time:

> var p = /a/gi;
> var s = "aaa";
> p.test(s)
true
> p.test(s)
true
> p.test(s)
true
> p.test(s)
false

See similar question: Why RegExp with global flag in Javascript give wrong results?

like image 125
Stefan Avatar answered Sep 22 '22 10:09

Stefan