当然,JSON不支持正则表达式字面量。
因此,
因此,
JSON.stringify(/foo/)
提供:
{ }
有什么解决方法吗?
JSON.stringify(/foo/)
提供:
{ }
有什么解决方法吗?
我认为这是最接近的:
RegExp.prototype.toJSON = function() { return this.source; };
JSON.stringify({ re: /foo/ }); // { "re": "foo" }
JSON.stringify
传递一个自定义替换函数,并将正则表达式转换为字符串(假设该表达式是数组或对象的一部分):JSON.stringify(value, function(key, value) {
if (value instanceof RegExp) {
return value.toString();
}
return value;
});
toString()
方法即可。instanceof RegExp
可靠吗?据我所知,一些浏览器过去将正则表达式视为Function的实例。 - Dagg Nabbittypeof
,并且是在旧版本的 Chrome 中。 - Blue Skies/foo/ instanceof RegExp
返回 true。 - Christian Ulbrichvar str = /([a-z]+)/.toString(); // "/([a-z]+)/"
JSON.stringify(/foo/,
function(k, v) {
if (v && v.exec == RegExp.prototype.exec) return '' + v;
else return v;
})
.source
属性的对象。并且你没有提供默认返回值。 - Blue Skiesv
不是 null
或 undefined
。 ;) - Blue Skies
+ (this.global ? "g" : "")
等方式添加修饰符。 - Blue Skies.toString
,我相信它会给你所有的东西。这个想法只是为了演示如何强制RegExps能够自己去JSON。 - AmadanRegExp.prototype
(并破坏封装性)更可取? - Dagg Nabbit.toJSON
选项。 - Blue Skies