Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stringifying a regular expression?

Of course, JSON does not support Regex literals.

So,

JSON.stringify(/foo/)

gives:

{ }

Any workarounds?

like image 698
user3025492 Avatar asked Nov 30 '22 02:11

user3025492


2 Answers

I think this is the closest you can get:

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

JSON.stringify({ re: /foo/ }); // { "re": "foo" }
like image 65
Amadan Avatar answered Dec 02 '22 17:12

Amadan


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.

like image 23
Felix Kling Avatar answered Dec 02 '22 15:12

Felix Kling