最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Stringifying a regular expression? - Stack Overflow

programmeradmin1浏览0评论

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 badges
Add a comment  | 

4 Answers 4

Reset to default 12

I 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; 
    })
发布评论

评论列表(0)

  1. 暂无评论