字符串化正则表达式?

use*_*492 4 javascript regex json

当然,JSON不支持Regex文字.

所以,

JSON.stringify(/foo/)
Run Code Online (Sandbox Code Playgroud)

得到:

{ }
Run Code Online (Sandbox Code Playgroud)

任何解决方法?

Ama*_*dan 11

我认为这是你能得到的最接近的:

RegExp.prototype.toJSON = function() { return this.source; };

JSON.stringify({ re: /foo/ }); // { "re": "foo" }
Run Code Online (Sandbox Code Playgroud)

  • +1,除了它没有给你修饰符.你需要添加`+(this.global?"g":"")`等等. (3认同)

Fel*_*ing 6

您可以将自定义替换函数JSON.stringify传递并将正则表达式转换为字符串(假设表达式是数组或对象的一部分):

JSON.stringify(value, function(key, value) {
    if (value instanceof RegExp) {
        return value.toString();
    }
    return value;
});
Run Code Online (Sandbox Code Playgroud)

如果您实际上不想/需要创建JSON,只需调用toString()表达式的方法即可.