Serialization of RegExp

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

    Yes, because there's no canonical representation for a RegExp object in JSON. Thus, it's just an empty object.

    edit — well it's 2018 now; the answers suggesting solutions using .toJSON() etc are probably fine, though I'd add the method to the prototype with

    Object.defineProperty(RegExp.prototype, "toJSON", {
      value: RegExp.prototype.toString
    });
    

    and so on. That ensures that the function name isn't enumerable, which makes the monkey-patch somewhat more hygienic.

提交回复
热议问题