Yun Li
Yun Li

Reputation: 427

javascript regex get different answer with same expression in Chrome console

I want to test Javascript Regex in Chrome Console. However, I get different answers with the same expression (refer to the picture). If I use original literal to test, the I can get right answer. What is the reason for that?

re = /^[a-z][0-9a-z]*$/g;
console.log(re.test("a34"));
console.log(re.test("a34"));
console.log(re.test("a34"));
console.log(re.test("a34"));
console.log(/^[a-z][0-9a-z]*$/g.test("a23"));
console.log(/^[a-z][0-9a-z]*$/g.test("a23"));

Upvotes: 0

Views: 97

Answers (1)

Blue
Blue

Reputation: 22911

Straight from the docs:

Use test() whenever you want to know whether a pattern is found in a string. test() returns a boolean, unlike the String.prototype.search() method, which returns the index (or -1 if not found). To get more information (but with slower execution), use the exec() method (similar to the String.prototype.match() method). As with exec() (or in combination with it), test() called multiple times on the same global regular expression instance will advance past the previous match.

Upvotes: 2

Related Questions