Anyone know of a good way to write a jQuery extension to handle query string parameters? I basically want to extend the jQuery magic ($)
function so I can do something like this:
$('?search').val();
Which would give me the value "test" in the following URL: http://www.example.com/index.php?search=test
.
I've seen a lot of functions that can do this in jQuery and Javascript, but I actually want to extend jQuery to work exactly as it is shown above. I'm not looking for a jQuery plugin, I'm looking for an extension to the jQuery method.
Best Answer
Why extend jQuery? What would be the benefit of extending jQuery vs just having a global function?
http://jsfiddle.net/gilly3/sgxcL/
An alternative approach would be to parse the entire query string and store the values in an object for later use. This approach doesn't require a regular expression and extends the
window.location
object (but, could just as easily use a global variable):http://jsfiddle.net/gilly3/YnCeu/
This version also makes use of
Array.forEach()
, which is unavailable natively in IE7 and IE8. It can be added by using the implementation at MDN, or you can use jQuery's$.each()
instead.