Take a look at the accessor properties on the RegExp
prototype such as source
and flags
. So you can do:
var myRe = new RegExp("weather", "gi")
var copyRe = new RegExp(myRe.source, myRe.flags);
For the spec see http://www.ecma-international.org/ecma-262/6.0/#sec-get-regexp.prototype.flags.
Serializing and deserializing regexps
If your intent in doing this is to serialize the regexp, such as into JSON, and then deserialize it back, I would recommend storing the regexp as a tuple of [source, flags]
, and then reconstituting it using new RexExp(source, flags)
. That seems slightly cleaner than trying to pick it apart using regexp or eval'ing it. For instance, you could stringify it as
function stringifyWithRegexp(o) {
return JSON.stringify(o, function replacer(key, value) {
if (value instanceof RegExp) return [value.source, value.flags];
return value;
});
}
On the way back you can use JSON.parse
with a reviver to get back the regexp.
Modifying regexps
If you want to modify a regexp while retaining the flags, you can create a new regexp with modified source and the same flags:
var re = /weather/gim;
var newre = new RegExp(re.source + "| is", re.flags);