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.

4

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.