gravityboy
gravityboy

Reputation: 817

Query string of referrer URL

Using php or javascript or regex, is there a quick (one-liner hopefully) to get the query string from the previous (referrer) URL?

Example,

User is at

www.sample.com?one

Then clicks link to go to

www.sample.com?two

From page two... I want to know the previous query string "one."

Upvotes: 1

Views: 24011

Answers (3)

plalx
plalx

Reputation: 43718

This perhaps?

var qs = document.referrer.split('?')[1] || '';

Looks like it's a contest :)

var r = document.referrer,
    indexOfQm = r.indexOf('?'),
    len = r.length;

/(?:[^?]+)\??(.*)/.exec(r)[1];

r.split('?').shift().pop() || '';

r.slice(indexOfQm === -1? len : indexOfQm - len + 1);

r.substring(indexOfQm === -1? len : indexOfQm + 1);

r.replace(/^.+?(?:\?(.*)|$)/, '$1');

r.split('').slice(indexOfQm + 1).join('');

[].reduce.call(r, function (res, c) {
    if (res.found) res.qs += c;
    else if (c === '?') res.found = true;

    return res;
}, { found: false, qs: '' }).qs;

Upvotes: 3

HaukurHaf
HaukurHaf

Reputation: 13796

You need to grab the referrer string on the server side.

If using PHP, it's as simple as this:

$referrer = $_SERVER['HTTP_REFERER'];

Then just split the string on the '?' sign to an array and you have the query-string at array index 1

Upvotes: 2

rninty
rninty

Reputation: 1082

Here’s one one-liner per line:

document.referrer.split("?").slice(1).join("?")
document.referrer.substring(document.referrer.indexOf("?") + 1)
/(?:\?(.+))?/.exec(document.referrer)[1]

referrer is not a good thing to rely on, though; people can and do turn them off. (I do.) Consider cookies or local storage.

Upvotes: 2

Related Questions