views:

44

answers:

2

http://stackoverflow.com/questions/3861970/regexpression-test
I have posted a problem in the above link

based on that i have done like bellow That too is error

var regExpression=new RegExp("^([a-zA-Z0-9_\-\.]+)$");
alert (regExpression.test("11aa"));
+1  A: 

You need to escape your \ since you're declaring it with a string, like this:

var regExpression=new RegExp("^([a-zA-Z0-9_\\-\\.]+)$"); 
                                           ^  ^ add these

You can test it here.

Nick Craver
i will have to replace all \ by \\ is there any such charecter(even it is not in this regex) to be replaced?
it would be better to just remove the existing backslashes.
SilentGhost
@SilentGhost - That would throw a script error.
Nick Craver
@Nick: would it? jsfiddle doesn't
SilentGhost
@SilentGhost - Sure it does, check your console: http://jsfiddle.net/nick_craver/juk48/1/ ...notice how you're not getting an alert, true *or* false?
Nick Craver
@NIck: well that has nothing to do with backslashes, it's just that `-` should be placed last (error is due to the bad range, I think). You see, still functions as normal.
SilentGhost
@SilentGhost - "just remove the existing backslashes" was your comment...that's what I was responding to, *that* would result in a script error. Yes changing the order as @Gumbo suggests works just fine, but that wasn't your comment.
Nick Craver
@Nick: it's the most obvious thing to do, so the script doesn't throw an error ;)
SilentGhost
@SilentGhost - You're missing the point entirely, you need to remove the backslashes *and* make other changes.
Nick Craver
+1. To answer @user444569's question in the first comment: Yes, **if** there are backslashes in the regex, they must themselves be escaped with backslashes if the regex is written in the form of a string literal (that is, as `new RegExp("...")` or `new RegExp('...')` instead of as `/.../`).
Alan Moore
+2  A: 

You can also use the literal RegExp syntax /…/:

var regExpression = /^([a-zA-Z0-9_\-\.]+)$/;

By the way: The . does not need to be escaped in character classes anyway. And if you put the range operator at the begin or the end of the character class or immediately after a character range, it doesn’t need to be escaped either:

var regExpression = /^([a-zA-Z0-9_.-]+)$/;
Gumbo