Using a string variable as a regular expression

In JavaScript, we add /gto the string without quotes to indicate a regular expression.

What if I have a string in a variable and want to use it as a regular expression?

Is it possible? If so, can someone show me some sample code?

Thank.

+3
source share
3 answers

Use this:

new RegExp("your regex here", "modifiers");

And note that /git is not a delimiter for a regular expression, it is a global modifier. The regular expression looks like this: /your regex here/modifiers. modifiersmay be a combination of g, iand m. Everything is explained here: http://www.regular-expressions.info/javascript.html

+6

, , . ( ) , :

new RegExp(yourRegExp, "modifiers").

, -.

+1

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


All Articles