Serialization of RegExp Serialization of RegExp json json

Serialization of RegExp


If somebody would be interested, there is a nice workaround. I don't think, that current behaviour is correct. For example, Date instance is not serialized to empty object like RegExp, though it is an object and also has no JSON representation.

RegExp.prototype.toJSON = RegExp.prototype.toString;// samplevar foo = { rgx: /qux$/ig, date: new Date }JSON.stringify(foo);//> {"rgx":"/qux$/gi","date":"2014-03-21T23:11:33.749Z"}"


Both JSON.stringify and JSON.parse can be customized to do custom serialization and deserialization by using the replacer and reviver arguments.

var o = {  foo: "bar",  re: /foo/gi};function replacer(key, value) {  if (value instanceof RegExp)    return ("__REGEXP " + value.toString());  else    return value;}function reviver(key, value) {  if (value.toString().indexOf("__REGEXP ") == 0) {    var m = value.split("__REGEXP ")[1].match(/\/(.*)\/(.*)?/);    return new RegExp(m[1], m[2] || "");  } else    return value;}console.log(JSON.parse(JSON.stringify(o, replacer, 2), reviver));