How to convert a JS regex literal inside a string to a RegExp

I have a JS regexp literal which is contained inside a dynamic string but it fully complains with the JS Regexp literal notation. Examples of what we could need to deserialize:

let regexInsideLiteral1 = "/foo/";
let regexInsideLiteral2 = "/foo\/bar/ig";

How can I get a JS regexp object from that without eval? Regex constructor from string considers the delimiters and modifiers to be part of the regex body.


ABOUT DUPLICATE: no, this is not the same question as the linked one. Scenario is different. Also, question already specifies why the RegExp constructor don’t solve the requirement.

Answer

Just identify the position of the last forward slash. The first character should also be a forward slash. The rest is just a matter of slicing the parts into the RegExp constructor.

function regexFromString(literal) {
    let i = literal.lastIndexOf("/");
    return literal[0] === '/' && RegExp(literal.slice(1, i), literal.slice(i+1));
}

let regex = regexFromString("/foo/");
console.log("this isfoook".split(regex));
regex = regexFromString("/foo\/bar/ig");
console.log("this isfoo/barok".split(regex));

Leave a Reply

Your email address will not be published. Required fields are marked *