Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

javascript - 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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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+'$');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...