I have found the following JS on the web.
It is a function to get url params values.
function get_url_param(param) {
param = param.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+param+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec(window.location.href);
if( results == null )
return '';
else
return results[1];
}
However always when I see a exec() function I think: Eeek!
So my question is: is it safe?
Side bet: If you think this function sucks and have a better option don’t hesitate to share 🙂
The above function uses the real url but I only need to parse a string which contains an URL.
Regexp#execis safe, albeit not a very nice interface.yeeep 🙂
This doesn’t use a
global regexp so you are only replacing one instance of each bracket;field[][]wouldn’t work. Also you don’t need the character group…param.replace(/\[/g, '\\[')would have worked. Or, the non-regexp replacement idiom,param.split('[').join('\\[').Then:
you’re not escaping nearly enough characters to be able to drop them into a regexp and have them mean their literal selves. See this question for a more watertight alternative.
Anyway this kind of regex hacking still isn’t a good way of parsing URLs/query strings. This doesn’t deal properly with
;or%-encoding, or+for space, and it may trip on parameter lookalikes elsewhere in the URL.Instead, let’s first get the query string on its own. If you have a link or location object, you can get it from the the
.searchproperty . If you only have a string URL, you can turn it into a link object to get this reliably:Now you can parse it into by dropping the leading
?, splitting on∨, then dropping the URL-decoded results into a JS Object:This makes it easy to look up parameters:
If you don’t need to read multiple values for a parameter, you could just do
lookup[name]= valueinstead of theif...[]...pushdance, to return single string values in the lookup instead of lists.