converting RegExp to String then back to RegExp

const regex = /asd/gi;

converting RegExp to String

const obj = {flags: regex.flags, source: regex.source};
const string = JSON.stringify(obj);

then back to RegExp

const obj2 = JSON.parse(string);
const regex2 = new RegExp(obj2.source, obj2.flags);

Requires ES6+.


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("/");
var restoredRegex = new RegExp(str.slice(1, lastSlash), str.slice(lastSlash + 1));

You can use the following before storage of your regex literal:

(new RegExp(regex)).source

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/source

Example:

regex = /asd/

string = (new RegExp(regex)).source
// string is now "asd"

regex = RegExp(string)
// regex has the original value /asd/