Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regExpression.test

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

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?

like image 259
Kuttan Sujith Avatar asked May 26 '26 09:05

Kuttan Sujith


1 Answers

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.

like image 69
August Lilleaas Avatar answered May 30 '26 13:05

August Lilleaas