1

I have a referring URL with a bunch of query string parameters. Here's my code so far:

var refURL=document.referrer;
var stock=refURL.substring(refURL.indexOf('?')+7, refURL.length);

This worked fine when I only had 1 query string parameter at the end of my URL. Now I have 3. I'd like to replace the second line so that the substring stops at the next "&".

var stock=refURL.substring(refURL.indexOf('?')+7, ????);

From there, I'd like to have another line that captures the next parameter and stores it as a variable. I can't use indexOf for that though, so how do I start from the "&" where I left off?

Thanks!

Kyle Suss
  • 457
  • 3
  • 7
  • 18
  • 1
    Try this question: http://stackoverflow.com/questions/901115/get-query-string-values-in-javascript – Rob Oct 05 '11 at 15:21

1 Answers1

1

There's much better ways to do query strings, so I'll discuss indexOf. It actually takes a second optional parameter of fromIndex.

var str = "com/?test=0&i=2&me=3&u=56";
var prevIndx = str.indexOf('?');
var query = {}, arr, result, next;

while(prevIndx != -1) {
    next = str.indexOf('&', prevIndx+1);
    if (next == -1) next = str.length;
    result = str.substring(prevIndx+1, next);
    arr = result.split('=');
    console.log(prevIndx)    
    query[arr[0]] = arr[1];
    prevIndx = str.indexOf('&', prevIndx+1);
}

That code isn't pretty, but it demonstrates the fromIndex parameter of indexOf

Joe
  • 80,724
  • 18
  • 127
  • 145