对正则表达式进行字符串化?
问题描述:
当然,JSON不支持Regex文字.
Of course, JSON does not support Regex literals.
所以
JSON.stringify(/foo/)
给予:
{ }
有什么解决方法吗?
答
我认为这是您可以获得的最接近的东西:
I think this is the closest you can get:
RegExp.prototype.toJSON = function() { return this.source; };
JSON.stringify({ re: /foo/ }); // { "re": "foo" }