Fátima Filipe Fátima Filipe - 1 year ago 146
Javascript Question

Transform regex inside string in real regex

I would like to know if is possible to transform a string-regex in a valid regex.

I have:

regex = `'/(.*)/g'`

And i need transform into


Because currently i'm trying to use with
and is returning undefined. I was trying to parse with JSON.parse, but of course... doesn't work.


Answer Source

You can use new RegExp() constructor, .replace() with RegExp /\/|'|g(?='$)/g, "" to match / or ' or g followed by ' folowed by end of input; pass "g" as second parameter to RegExp()

var regex = `'/(.*)/g'`;
var re = new RegExp(regex.replace(/\/|'|g(?='$)/g, ""), "g");

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download