Serialization of RegExp

前端 未结 6 1764
北荒
北荒 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

    Here's how I solved this issue:

    Serialize it as a string:

    var pattern = /foobar/i;
    var serialized = JSON.stringify(pattern.toString());
    

    Then rehydrate it using another regex:

    var fragments = serialized.match(/\/(.*?)\/([a-z]*)?$/i);
    var rehydrated = new RegExp(fragments[1], fragments[2] || '');
    

    Preserves the pattern and flags - hope this helps someone!

提交回复
热议问题