0

why does this code return false:

var text = "3b3xx";
if(text.match("/^\d?b\d+xx$/")) {
    return true;
}
return false;

I can not see any problem with my regular expression.. I want to return true, if the string starts with any numbers, followed by "b", followed by any numers, followed by "xx".

4 Answers 4

7

That's a string, not a regex.

Remove the "".

Sign up to request clarification or add additional context in comments.

1 Comment

@groh Please watch the language. This is a classy place, and young people browse it regularly. And get some sleep. :-)
2

You are passing a string where a regular expression is expected.

var text = "3b3xx";
if(text.match(/^\d?b\d+xx$/)) {
    return true;
}
return false;

5 Comments

Actually, you can pass a string, and the match method will convert it to a RegExp object internally, e.g. : if (text.match("^\\d?b\\d+xx$")) but anyway, in this case is completelly unnecessary - since the pattern is fixed-, I would even return /^\d?b\d+xx$/.test(text); to remove the if statement.
@CMS and the match method will convert it to a RegExp object internally": not in my Chrome it won't.
@KooiInc: Really? In which version of Chrome are you testing? Try: 'a'.match('\\w')[0] == 'a'. If it doesn't work, it's an implementation bug, the behavior is completely described on the ECMAScript Specification (15.5.4.10 - see Step 4 -)
using Chrome 12.0.742.112. But forgot to escape the escapes :}. Still, I wouldn't use this javascript 'dynamic typing feature'.
@KooiInc: Yeah, I just mentioned it because it's a little known fact, and the answer said that a RegExp object was "expected", in fact, you could pass any non-regexp object, it will be converted to String, and it will be used to build the RegExp object behind the scenes. Cheers.
2

Why not trying this:

var text = "3b3xx";
return text.match(/^\d?b\d+xx$/);

Comments

1

Just lose the quotes around your regex.

Regex is an object in Javascript, not a String.

/^\d?b\d+xx$/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.