I've found plenty of articles on StackOverflow that mention fast ways to parse query string's in Javascript, but what I haven't found is how to handle both &
and ;
as a delimiter.
Now, I assume, only one of those gets set as the delimiter for the query string. Take for instance, the following query string:
index.php?Param1=value&Param2=value;Param3=value
Which is the delimiter?
- Is it
&
, or is it;
? - Is it the first recognized delimiting character, or is it
&
takes precedence over;
? - Are both treated as delimiters, and all three parameters from the example parsed?
In Javascript, I have historically been using the following function:
/**
* Gets the value of a parameter from a URI.
* @param href The full URI to search. Must at least start with a ? query string delimiter.
* @param key The key of the param for which to retrieve the value.
* @param def A default value to return in the case that the key cannot be found in the query string.
* @return The value of the param if the key is found, otherwise returns def.
*/
function getURIParam(href, key, def) {
if (arguments.length == 2) def = null;
var qs = href.substring(href.indexOf('?') + 1);
var s = qs.split('&');
for (var k in s) {
var s2 = s[k].split('=');
if (s2[0] == key)
return decodeURIComponent(s2[1]);
}
return def;
}
That just splits out each key/value pair based on &
. It works great, so long as the delimiter is always &
. As we know, however, that is not always the case, nor should be enforced, as the RFC allows for ;
as well.
So, in order to handle both &
and ;
as a delimiter, should I first search for an indexOf("&")
and if no occurrence is found, set the delimiter to ;
?
What is the proper way of parsing a URL based on the rule that the delimiter can be either &
or ;
?
Here is the W3C Recommendation on server being able to handle both &
and ;
.
We recommend that HTTP server implementors, and in particular, CGI implementors support the use of ";" in place of "&" to save authors the trouble of escaping "&" characters in this manner.
Here is RFC 1738 which defines the URI.