Use Variable Pattern to Match Regular Expression in Javascript

Use Variable Pattern to Match Regular Expression in Javascript

We all know that to match a particular regular expression in JS, you simply do this:

"foo".match(/foo/i);

However, if you want “foo” to be a variable:

var foo = 'foo';
"foo".match(/foo/i);

This becomes confusing and I don’t think it works.

To do it properly, do the following instead:

var filter = new RegExp('foo');
"foo".match(filter);

Leave a Reply

Your email address will not be published.

My new Snowflake Blog is now live. I will not be updating this blog anymore but will continue with new contents in the Snowflake world!