PDA

View Full Version : [DHTML] Url Variable/Value Lookup



magicgavin
07-17-2007, 06:49 PM
1) CODE TITLE: Url Variable/Value Lookup

2) AUTHOR NAME/NOTES: Gavin Delphia 2007

3) DESCRIPTION:

This script can retrieve the value of variables passed through the url or it can do the reverse and find the variable with specified value.
It can also check if the variable or value even exists in the url.
It is compatible with firefox and Internet Explorer.

UrlVariable(variable,0) - Returns the value of the variable or false is variable not found

UrlVariable(value,1) - Returns the first variable found that matches the value or false is value not found


4) http://javag.f2g.net/demo.html?test=1&day=monday&week=50&color=blue&age=18

Twey
07-18-2007, 12:06 AM
Woah Nelly, nice overkill but I'm afraid it doesn't comply with the standards very well. The semicolon (;) is a valid GET parameter separator as well. Your functions plus that feature can be written with one regex each:
function UrlVariable(varname, isvalue) {
var m = location.href.substr(location.href.indexOf("?") + 1).match(new RegExp(isvalue ? "([^;&]+)=" + varname : varname + "=([^;&]+)"));
return m && m[1];
}If we wanted to be really standards-compliant, though, we'd have to work with multiple values to the same variable too:
function UrlVariable(varname, isvalue) {
var m = location.href.substr(location.href.indexOf("?") + 1).match(new RegExp(isvalue ? "([^;&]+)=" + varname : varname + "=([^;&]+)", "g")),
r = [];

for(var i = 0, n = m.length; i < n; ++i)
r.push(isvalue ? m[i].substr(0, m[i].indexOf("=")) : m[i].substr(m[i].indexOf("=") + 1));

return r;
}Either way, the code doesn't come close to looking like that mass of string manipulation you've got going on there.

There was a much more elegant implementation that mwinter wrote at one point, but I can't find it now.

shachi
07-19-2007, 02:51 PM
Here you go Twey: http://www.dynamicdrive.com/forums/showthread.php?t=11883

EDIT: More specific link: http://www.dynamicdrive.com/forums/showpost.php?p=49564&postcount=25

Twey
07-19-2007, 06:47 PM
Ah yes, I forgot about # again, didn't I :p Mike's doesn't handle multiple values, though, and has one noticeable bug (exhibited with URLs such as page.html?var1=val1#;var2=val2)... I'd be inclined to adapt mine:
function urlVariable(varname, isvalue) {
var m = location.href.substr(location.href.indexOf("?") + 1),
r = [];

m = (m.substr(0, location.href.indexOf("#")) || m).match(new RegExp(isvalue ? "([^;&]+)=" + varname : varname + "=([^;&]+)", "g"));

for(var i = 0, n = m.length; i < n; ++i)
r.push(decodeURIComponent(isvalue ? m[i].substr(0, m[i].indexOf("=")) : m[i].substr(m[i].indexOf("=") + 1)));

return r;
}

shachi
07-20-2007, 10:26 AM
Twey: what's the second argument(isvalue) for?

Twey
07-20-2007, 11:38 AM
The original code had two uses: to find the value of a property given its name, or to find the name of a property given its value. isvalue is the trigger to switch to the latter.