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));
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:
Working example here: http://jsfiddle.net/jfriend00/5pa2j/