Serialization of RegExp

前端 未结 6 1777
北荒
北荒 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:31

    RegExp.prototype.toJSON = RegExp.prototype.toString;
    
    var regexp = /^[0-9]+$/;
    var foo = { rgx: regexp.source, date: new Date };
    var stringified = JSON.stringify(foo);
    new RegExp(JSON.parse(stringified).rgx)
    

提交回复
热议问题