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?
You need to use new RegExp like this:
var bar = "foo",
re = new RegExp(bar)
bar.match(re) //returns ["foo"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With