Of course, JSON does not support Regex literals.
So,
JSON.stringify(/foo/)
gives:
{ }
Any workarounds?
Of course, JSON does not support Regex literals.
So,
JSON.stringify(/foo/)
gives:
{ }
Any workarounds?
Share Improve this question asked Nov 29, 2013 at 0:13 user3025492user3025492 3,0534 gold badges20 silver badges19 bronze badges4 Answers
Reset to default 12I 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.
Although JavaScript objects allow you to put regex as values, JSON does not as it is meant to store only data, not code.
As a workaround, you could convert your regular expression to a string using the toString()
method.
var str = /([a-z]+)/.toString(); // "/([a-z]+)/"
You can use a replacer function:
JSON.stringify(/foo/,
function(k, v) {
if (v && v.exec == RegExp.prototype.exec) return '' + v;
else return v;
})