开发者

Referring URL Query String Parameters w/ Javascript

开发者 https://www.devze.com 2023-04-11 12:46 出处:网络
I have a referring URL with a bunch of query string parameters. Here\'s my code so far: var refURL=document.referrer;

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 paramet开发者_开发问答er 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!


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

0

精彩评论

暂无评论...
验证码 换一张
取 消