views:

40

answers:

2
+2  Q: 

regExpression.test

<script language="javascript">

alert("......");
var regExpression = /^([a-zA-Z0-9_\-\.]+)$/; //line 2
//// var regExpression = "/" + "^([a-zA-Z0-9_\-\.]+)$" + "/"; //line 3
alert (regExpression.test("11aa"));
alert("......2");

</script>

The above code is working fine.
But if we replace line 2 by line 3 then it is not working
why? i am in a situation like I want to create the var only by appending(the expression come dynamically) so what should i do?

A: 

If you like to create a RegExp dynamically, use new RegExp(). This allows you to build the expression with string-functions

Dr.Molle
+2  A: 

Line 3 sets regExpression to a string. Strings does not have a test method. You need to turn the string into a RegExp.

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

Omit the slashes, as they are not part of the regexp itself.

August Lilleaas
this also is not working
That's because the backslashes should have been doubled, as explained by @Nick Craver in his answer to your followup question, http://stackoverflow.com/q/3864657/20938
Alan Moore
Thanks for the heads up, updated my answer.
August Lilleaas