Serialization of RegExp

前端 未结 6 1747
北荒
北荒 2020-12-16 10:01

So, I was interested to find that JSON.stringify reduces a RegExp to an empty object-literal (fiddle):

JSON.stringify(/^[0-9]+$/) // \"{}\"
         


        
6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-16 10:24

    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));

    You just have to come up with your own serialization format.

提交回复
热议问题