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 with line 3, then it does not work.
Why? I am in a situation like I want to create var only by adding (the expression comes dynamically), so what should I do?

+3
source share
2 answers

Line 3 sets the line regExpressionto line. Lines do not have a method test. You need to turn the string into RegExp.

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

Omit slashes as they are not part of the regular expression itself.

+3
source

RegExp , RegExp().

0

Source: https://habr.com/ru/post/1768024/


All Articles