You can use either regular expressions or ordinary string manipulations. A while back I wrote a script which retrieves all the GET variables from the query string and puts them in _GET just like in PHP, and it does almost all the string manipulations for you. (I think the only thing it doesn't do is reorganize _GET into a new URL, but that wouldn't be too difficult to write.)
Code:
window.GET = function(){
var array = window.location.search.split(/&;/):
//URLs can be like either "sample.html?test1=hi&test2=bye" or
//"sample.html?test1=hi;test2=bye"
window._GET = {};
for(var i = 0; i < array.length; i++){
var assign = array[i].indexOf('=');
if(assign == -1){
_GET[array[i]] = true;//if no value, treat as boolean
}else{
_GET[array[i].substring(0, assign)] = array[i].substring(assign + 1);
}
}
}
If you're interested in how it works, read on; if not, scroll down to the instructions.
Code:
var array = window.location.search.split(/&;/):
"Get the query string (or 'search string'), if any, from the URL and make array equal to the pieces of that string divided by '&'s and ';'s.""Make _GET a global variable and put an empty object (so no fields are reserved for array things like 'length') in it."
Code:
for(var i = 0; i < array.length; i++){
"For each of the indices in array,...
Code:
var assign = array[i].indexOf('=');
"Get the position of '=' in the current array element.""If the current array element doesn't contain '=', ..."
Code:
_GET[array[i]] = true;
"In the _GET object, associate the value of this array element with a boolean value of true.""Otherwise,..."
Code:
_GET[array[i].substring(0, assign)] = array[i].substring(assign + 1);
"In the _GET object, associate the value of this array element from its first character to that '=' (the name of the GET parameter) with the value of the same array element from just after that '=' to the end (the value of the GET parameter)."
This is how you make sure all GET parameters are available from anywhere in your script:
Simple GET() would also work, unless a variable with an identical name were declared locally. (If another variable named GET is declared globally, one of these two variables would overwrite the other, and the function might not work.)
So, if the URL is example.com/test.html?test1=hi&test2=bye, then this:
Code:
window.GET();
alert(_GET['test1']);
alert(_GET.test1);
alert(_GET['test2']);
alert(_GET.test2);
will alert "hi" twice, then "bye" twice.
Bookmarks