Reputation: 39395
Given the following code:
var a = 'somegarbage=http://somesite.com/foo/bar/&moregarbage';
var result = a.match(/http.+\//g);
Produces the expected result: ["http://somesite.com/foo/bar/"]
Now, if I do this:
var a = 'somegarbage=http://somesite.com/foo/bar/&moregarbage';
var config = JSON.parse('{"filter":"/http.+\\//g"}'); //notice the extra '\'?
var result = a.match(config.filter);
It returns null. I presume that it has to do with the string escaping of \
in JSON. I feel like I'm missing a simple solution. How can I fix this? Thanks.
Edit:
I have also tried this and it doesn't work:
var a = 'somegarbage=http://somesite.com/foo/bar/&moregarbage';
var config = JSON.parse('{"filter":"/http.+\\//g"}'); //notice the extra '\'?
var result = a.match(new RegExp(config.filter));
Upvotes: 0
Views: 5530
Reputation: 25145
Use RegExp
var a = 'somegarbage=http://somesite.com/foo/bar/&moregarbage';
var config = JSON.parse('{"filter":"http.+/"}');
var result = a.match(new RegExp(config.filter, "g"));
Upvotes: 1
Reputation: 707446
JSON doesn't accept regular expressions as a type. So, you need to just put the regular expression in a string (with the leading / and trailing / and then after you parse it, you need to feed the regular expression to new RegExp(str) to turn it into a regular expresssion.
You can do it like this:
var a = 'somegarbage=http://somesite.com/foo/bar/&moregarbage';
var x = JSON.parse('{"filter":"http.+/", "flags": "g"}');
x.filter = new RegExp(x.filter, x.flags);
var result = a.match(x.filter);
alert(result);
Working example here: http://jsfiddle.net/jfriend00/5pa2j/
Upvotes: 2
Reputation: 46647
In javascript, the /.../
syntax for RegExp is a special syntax, not just a string. If you want to to store your regex as a string in JSON, you need to use the RegExp constructor.
var config = JSON.parse('{"filter":"/http.+\\//g"}');
var result = a.match(new RegExp(config.filter));
Upvotes: 1