Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I format a regex that includes a variable?

I have the following regex that works fine if I hard-code a value such as "foo":

/foo/

But what if "foo" is a variable? How to I write the regex for that? For example:

var bar = "foo";

I can't get /bar/ to work. How can I format this to work when "bar" is a variable?

like image 676
Chris Paterson Avatar asked Jul 12 '26 10:07

Chris Paterson


1 Answers

You need to use new RegExp like this:

var bar = "foo",
    re = new RegExp(bar)

bar.match(re) //returns ["foo"]
like image 155
bottens Avatar answered Jul 15 '26 02:07

bottens