0

I am attempting to extract 2 parameters from a URL string using jQuery and just do not have enough experience to figure it out.

Here is a sample of a URL:

http://awebsite.com/index.html?ref=toys&zip=30003

I would like to grab and assign these 2 parameters as variables. Here is what I've tried so far:

var url = window.location.href;
var params = url.split('?');
var ref = params[1].split('=')[1];
var zip = params[1].split('&')[1];

So that var ref would be toys and var zip would be 30003

Any help appreciated.

user13286
  • 3,027
  • 9
  • 45
  • 100
  • You can find yout answer here: http://stackoverflow.com/questions/19491336/get-url-parameter-jquery – sticksu Oct 24 '14 at 18:41
  • Possible Duplicate : http://stackoverflow.com/questions/19491336/get-url-parameter-jquery – Ryan Oct 24 '14 at 18:42
  • possible duplicate of [How can I get query string values in JavaScript?](http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript) – Mehdi Oct 24 '14 at 18:43
  • Thanks, but is there any way to do it more along the lines of what I have? That seems like a lot of code just to grab 2 parameters(not that it would affect load time, just want to keep it as clean as possible). – user13286 Oct 24 '14 at 18:43

1 Answers1

1

Split the query string on & so that you get each parameter in a string, then split each one on =.

Example:

var url = 'http://awebsite.com/index.html?ref=toys&zip=30003';

var params = url.substr(url.indexOf('?') + 1).split('&');
var ref = params[0].split('=')[1];
var zip = params[1].split('=')[1];

// show result in StackOverflow snippet
document.writeln(ref);
document.writeln(zip);
Guffa
  • 687,336
  • 108
  • 737
  • 1,005