tags:

views:

94

answers:

3

I am looking to use javascript to extract the GET parameters from a user inputed url.

For example is a user enters a url say:

http://www.youtube.com/watch?v=ee925OTFBCA

I could get the v parameter

'ee925OTFBCA' as a variable

Thanks in Advance.

A: 

From here:

function getURLParam(strParamName){
  var strReturn = "";
  var strHref = window.location.href;
  if ( strHref.indexOf("?") > -1 ){
    var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
    var aQueryString = strQueryString.split("&");
    for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
      if (
aQueryString[iParam].indexOf(strParamName.toLowerCase() + "=") > -1 ){
        var aParam = aQueryString[iParam].split("=");
        strReturn = aParam[1];
        break;
      }
    }
  }
  return unescape(strReturn);
}

To use it:

 var v = getURLParam('v')
fmark
location.search gives you the ?xxxx part - if no location.search, no questionmark there
mplungjan
+1  A: 

This should do the trick

// include this somewhere available 
var Query = (function(){
    var query = {}, pair, search = location.search.substring(1).split("&"), i = search.length;
    while (i--) {
        pair = search[i].split("=");
        query[pair[0]] = decodeURIComponent(pair[1]);
    }
    return query;
})();


var v= Query["v"]

This only runs its computation once and creates an object with name/value pairs corresponding to those supplied as parameters

Sean Kinsey
Nice one - and only needs to decode once as opposed to the other posts here.
mplungjan
This doesn't work for multiple values. It works to answer this specific question, but not as a general purpose solution.
Guffa
Guffa: what? Go read up on your DOM/javascript. The search field was never intended to convey multiple parameters with identical names.
Sean Kinsey
A: 

You can use a function like this:

function querystring(key) {
   var re=new RegExp('(?:\\?|&)'+key+'=(.*?)(?=&|$)','gi');
   var r=[], m;
   while ((m=re.exec(document.location.search)) != null) r.push(m[1]);
   return r;
}

Example:

var v = querystring('v')[0];

The function returns an array with all the values found in the query string. If you have a query string like ?x=0&v=1&v=2&v=3 the call querystring('v') returns an array with three items.

Guffa
window.location.search is the one to use in my opiniondocument.location is now document.URL
mplungjan