Of course, JSON does not support Regex literals.
So,
JSON.stringify(/foo/)
gives:
{ }
Any workarounds?
I think this is the closest you can get:
RegExp.prototype.toJSON = function() { return this.source; };
JSON.stringify({ re: /foo/ }); // { "re": "foo" }
You can pass a a custom replacer function to JSON.stringify
and convert the regular expression to a string (assuming that the expression is part of an array or object):
JSON.stringify(value, function(key, value) {
if (value instanceof RegExp) {
return value.toString();
}
return value;
});
If you don't actually want/need to create JSON, just call the toString()
method of the expression.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With