user3025492
user3025492

Reputation: 3043

Stringifying a regular expression?

Of course, JSON does not support Regex literals.

So,

JSON.stringify(/foo/)

gives:

{ }

Any workarounds?

Upvotes: 5

Views: 4067

Answers (4)

Guilherme Sehn
Guilherme Sehn

Reputation: 6787

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]+)/"

Upvotes: 2

Dagg Nabbit
Dagg Nabbit

Reputation: 76736

You can use a replacer function:

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

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816374

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.

Upvotes: 6

Amadan
Amadan

Reputation: 198324

I think this is the closest you can get:

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

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

Upvotes: 12

Related Questions