views:

94

answers:

3

Suppose you have a URL:

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

How would you extract the value of the where parameter (in this case when)?

This is what I came up with -- I'm wondering if there's 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];
}
+5  A: 

use jquery.query and have fun :)

you can simply use:

var w = $.query.get("where");
TheVillageIdiot
TheVillageIdiot, is this part of the main jQuery library. Pretty useful...
David Andres
thanks @David I was using separate plugin for it :(
TheVillageIdiot
Query string object is an extension creates a singleton query string object for quick and readable query string modification and creation. This plugin provides a simple way of taking a page's query string and creating a modified version of this with little code.
ranonE
A: 

If you are left without jQuery, here is a function I use:

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(defaulted to window) if you need to read iframe parameters.

Mic
A: 

I use 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 & easiest for jQuery :P... YAY, I learned something new today :) But you should still check out the plugin, it's nice in that it will return any part of the URL including data from a string.

fudgey