开发者

regExpression.test

开发者 https://www.devze.com 2023-01-19 05:03 出处:网络
var regExpression = /^([a-zA-Z0-9_\\-\\.]+)$/; //line 2 //// var regExpression = \"/\" + \"^([a-zA-Z0-9_\\-\\.]+)$\" + \"/\"; //line 3
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 i开发者_JS百科t 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?


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消