Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is RegExp.test() not consistent?

I do not understand why the javascript RegExp.test() method do no return the same result every time I call it.

Given the following javascript variables

var opener = '<span[^>]*>';
var regexo = new RegExp('^'+opener+'$', "g");

I do the following:

alert(regexo.test('<span class="outer">')); // true
alert(regexo.test('<span class="inner">')); // false
alert(regexo.test('<span class="inner">')); // true

I tested it in Firefox 24.0 and IE8 with the same strange result.

Why is the result true, false, true instead of true, true, true ?

like image 517
fluminis Avatar asked Dec 07 '22 04:12

fluminis


1 Answers

That's because you use the g flag. It turns the regexp object into an iterator, whose state changes with each call.

You don't need the g flag here, so just remove it :

var regexo = new RegExp('^'+opener+'$');
like image 51
Denys Séguret Avatar answered Dec 22 '22 10:12

Denys Séguret