user13286
user13286

Reputation: 3075

Assistance extracting parameters from URL using jQuery

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.

Upvotes: 0

Views: 160

Answers (1)

Guffa
Guffa

Reputation: 700562

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);

Upvotes: 1

Related Questions