Reputation: 9027
I'd like to extract from the url of a Google search the keyword of the search (e.g. for the keyword "car" : http://www.google.com/webhp?hl=en#sclient=psy&hl=en&site=webhp&source=hp&q=car&aq ... (here car is between "q=" and "&aq" but I noticed that the tokens might change ["&ie" instead of "&aq"]).
Being new at regex and Google search I haven't found so far the solution, does someone know how to do this please ?
Bruno
Upvotes: 9
Views: 6315
Reputation: 1041
function getParameterByName(name,url) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(url);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
alert(getParameterByName('q','https://www.google.com/search?q=buy+a+pc&oq=buy+a+pc&aqs=chrome..69i57j5j0l2j69i61.1674j0&sourceid=chrome&ie=UTF-8#psj=1&q=buy+a+pc'));
Upvotes: 1
Reputation: 1124
Below sample code works for me for a single parameter and current URL but can be modified as per requirement.
function extract( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
just use it as shown below,
var result= extract("your parameter name");
Upvotes: 0
Reputation: 64700
You don't need a regular expression for this. Modified from http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html:
function getUrlVars(href)
{
var vars = [], hash;
var hashes = href.slice(href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
You can then do this:
var v = getUrlVars("http://www.google.com/webhp?hl=en#sclient=psy&hl=en&site=webhp&source=hp&q=car&aq");
var q = v.q;
Upvotes: 19