Regex string?

Of course, JSON does not support Regex literals.

So,

JSON.stringify(/foo/)

gives:

{ }

Any workarounds?

+3
source share
4 answers

I think this is the closest you can get:

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

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

You can pass aa custom replace function toJSON.stringify and convert the regular expression to a string (assuming that this 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 really do not want / should not create JSON, just call the toString()expression method .

+6
source

JavaScript , JSON , , .

As a workaround, you can convert your regex to string using a method onString().

var str = /([a-z]+)/.toString(); // "/([a-z]+)/"
+2
source

You can use the replacer function :

JSON.stringify(/foo/, 
    function(k, v) { 
        if (v && v.exec == RegExp.prototype.exec) return '' + v; 
        else return v; 
    })
+1
source

All Articles