Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression test can't decide between true and false (JavaScript)

I get this behavior in both Chrome (Developer Tools) and Firefox (Firebug). Note the regex test returns alternating true/false values:

> var re = /.*?\bbl.*\bgr.*/gi;
undefined
> re
/.*?\\bbl.*\\bgr.*/gi
> re.test("Blue-Green");
true
> re.test("Blue-Green");
false
> re.test("Blue-Green");
true
> re.test("Blue-Green");
false

However, testing the same regex as a literal:

> /.*?\bbl.*\bgr.*/gi.test("Blue-Green");
true
> /.*?\bbl.*\bgr.*/gi.test("Blue-Green");
true
> /.*?\bbl.*\bgr.*/gi.test("Blue-Green");
true
> /.*?\bbl.*\bgr.*/gi.test("Blue-Green");
true

I can't explain this and it's making debugging very difficult. Can anyone explain this behavior?

like image 295
nw. Avatar asked Apr 19 '10 18:04

nw.


People also ask

Which is faster regex match or RegExp test?

The match() method retrieves the matches when matching a string against a regular expression. Use . test if you want a faster boolean check.

What does .test do in JavaScript?

test() The test() method executes a search for a match between a regular expression and a specified string. Returns true or false .

How do you check whether a string matches a regex in JavaScript?

If you need to know if a string matches a regular expression RegExp , use RegExp.prototype.test() . If you only want the first match found, you might want to use RegExp.prototype.exec() instead.

How do I check if a string is regular expression?

Use the test() method to check if a regular expression matches an entire string, e.g. /^hello$/. test(str) . The caret ^ and dollar sign $ match the beginning and end of the string. The test method returns true if the regex matches the entire string, and false otherwise.


1 Answers

/g (global) regexps will do that, yes.

See this question.

When you write a literal, you're getting a new regexp object every time, so losing the lastIndex state associated with the old object.

like image 143
bobince Avatar answered Nov 03 '22 17:11

bobince