Stringifying a regular expression?

javascript, json, regex

Solution

I think this is the closest you can get:

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

JSON.stringify({ re: /foo/ }); // { "re": "foo" }

Problem

Of course, JSON does not support Regex literals. So, ``` JSON.stringify(/foo/) ``` gives: ``` { } ``` Any workarounds?

Original source