Best way to get the value of a given URL parameter using Javascript / jQuery?

Let's say you have a url:

http://www.example.com/whatever?this=that&where=when

      

How would you retrieve the parameter value where

(in this case when

)?

Here's what I came up with - I'm wondering if there is a better solution:

$.fn.url_param_value = function(param) {
  var url = $(this).attr('href');
  var regex = new RegExp(param + "=");

  return $.grep(url.split("?")[1].split("&"), function(a) {
    return a.match(regex);
    })[0].split("=")[1];
}

      

+2


source to share


3 answers


use jquery.query and have fun :)

you can just use:



var w = $.query.get("where");

      

+5


source


If you are left without jQuery, here is the function I'm using:

function urlParam(name, w){
    w = w || window;
    var rx = new RegExp('[\&|\?]'+name+'=([^\&\#]+)');
    var val = w.location.href.match(rx);
    return !val ? '':val[1];
}

      



w is an optional parameter (default for a window) if you need to read the iframe parameters.

+1


source


I am using this bit of javascript from Netlobo.com

function gup( 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];
}

      

or if you are looking for a plugin try jQuery URL Parser

* Edit: Hmm, nm I guess TheVillageIdiot's suggestion is the best and lightest for jQuery: P ... YAY, I learned something new today :) But you should still check the plugin, nice it will return any part URL including data from string.

0


source







All Articles