2

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];
}

3 Answers 3

5

use jquery.query and have fun :)

you can simply use:

var w = $.query.get("where");
Sign up to request clarification or add additional context in comments.

1 Comment

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.
1

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.