When I have a url like this:
http://server/site?firstname=Jack&lastname=Daniels
I understand that in my JavaScript a query for firstname should return "Jack".
But what should the query for firstname return in the following cases:
http://server/site?lastname=Daniels
http://server/site?firstname&lastname=Daniels
http://server/site?firstname=&lastname=Daniels
[Edit] To answer some of the comments: all of the above are legal querystrings, my question is not about how to retrieve the parameters but how to interpret them.
For the record, I parse querystrings with the following regular expression that covers all cases:
/([^?=&;]+)(?:=([^&;]*))?/g
Apparently there's a very popular question on how to retrieve querystring parameters, but the answer is incorrect (or at least not addressing edge cases).
[Update] My choice based on the answers from @Bergi and @zzzzBov:
http://server/site?lastname=Daniels => firstname: undefined
http://server/site?firstname&lastname=Daniels => firstname: true
http://server/site?firstname=&lastname=Daniels => firstname: ""
http://server/site?firstname=Jack&lastname=Daniels => firstname: "Jack"
A side effect is that I had to slightly modify my regex, as with the above rules the =
sign needs to be captured:
/([^?=&;]+)(=[^&;]*)?/g