Friday 23 August 2019

javascript - Extracting search queries from URL in jQuery











http://www.example.org/search?q=example&another=test&again=more


How can I create three sepearate variables in jQuery with the values example, test, and more?



In other words, how can I extract a query from a URL based on its position (first, second, third, etc.) in the URL or based on the &another= part (not sure what it's called) of the query?



Answer



I use this method:



var query        = window.location.split('?')[1]; // or http://www.example.org/search?q=example&another=test&again=more
var query_obj = unserialize(query);

function unserialize(query) {
var pair, params = {};
query = query.replace(/^\?/, '').split(/&/);
for (pair in query) {

pair = query[pair].split('=');
params[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
return params;
}


So you'll have your variables in the query_obj like this: query_obj.test



I found the function over the internet a while ago so I can't provide a link. Sorry and thanks to whoever published it first.



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...