converting RegExp to String then back to RegExp

If you don’t need to store the modifiers, you can use Regexp#source to get the string value, and then convert back using the RegExp constructor.

var regex = /abc/g;
var str = regex.source; // "abc"
var restoreRegex = new RegExp(str, "g");

If you do need to store the modifiers, use a regex to parse the regex:

var regex = /abc/g;
var str = regex.toString(); // "/abc/g"
var parts = /\/(.*)\/(.*)/.exec(str);
var restoredRegex = new RegExp(parts[1], parts[2]);

This will work even if the pattern has a / in it, because .* is greedy, and will advance to the last / in the string.

If performance is a concern, use normal string manipulation using String#lastIndexOf:

var regex = /abc/g;
var str = regex.toString(); // "/abc/g"
var lastSlash = str.lastIndexOf("https://stackoverflow.com/");
var restoredRegex = new RegExp(str.slice(1, lastSlash), str.slice(lastSlash + 1));

Leave a Comment