I have been using the following function to get regular parameters from the current url:
function getURLParameter(name) {
return decodeURI(
(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}
However, I want to get the GET parameter ‘imgurl’ from a string that will follow the format for the url here.
When I change that function to handle regular strings:
function getURLParameter(name, givenstring) {
return decodeURI(
(RegExp(name + '=' + '(.+?)(&|$)').exec(givenstring.search)||[,null])[1]
);
}
It returns null. I even made a userscript go to the url that I just gave you and I used the first function to try to get that ‘imgurl’ parameter, but it was unable to do so. I also got rid of the colons in that url, but obviously that did nothing.
What is throwing this function off about this string format?
location.searchis the query-string part of the current URL. If you want to replace that with an arbitrary string variablegivenstring, then you would replacelocation.searchwithgivenstring, not withgivenstring.search. So:By the way, your function will misbehave if (for example) the string is
foobar=baz&bar=bipand the parameter of interest isbar. It will find the first instance ofbar=..., which in this case isbar=bazrather thanbar=bip. You can fix that by using(^|&):(Your function will also misbehave if
namehas any special characters in it — either special in URLs or special in regexes — but I’m guessing that you have enough control overnamethat you can make certain that’s not going to be an issue?)