|
|
Joined: Dec 1999
Posts: 30,867
Master Elite Member
|
QueryString_ToObj(QueryString)
function QueryString_ToObj(qs, def) {
/*
Purpose
Used to parse a query string to an array.
Parameters
qs (string) = The query string we're working with.
This may optionally contain a leading question mark (for convenience).
def (any) = The value assigned to query string elements with no value.
Examples: Assume def = "abc"
"?name&age=25" returns { name: "abc", age: "25" }
"?name=&age=25" returns { name: "abc", age: "25" }
Default if undefined: null
Return (object)
Returns an object containing all elements in the specified query string as properties of the object.
If a query string element with the same name is specified more than once,
the corresponding object property is an array containing each corresponding value.
Example: "?firstname=russ&firstname=sue&lastname=smith" returns {firstname: ["russ", "sue"], lastname: "smith"}
If an element has no value assigned, it returns the specified default value (def).
Example: assume def = null: "?newuser" returns {newuser: null}
Example: assume def = null: "?newuser=" returns {newuser: null}
Example: assume def = '': "?newuser" returns {newuser: ''}
Returns an empty object if:
- The specified query string contains only whitespace, or
- The specified query string is not a string.
All element values are properly unescaped.
Notes
You can determine the total number of elements returned using this code:
Count = Object.keys(MyQueryString).length;
You can determine if an element is an array with this code:
if (Object.prototype.toString.call(MyQueryString['names']) === '[object Array]') { // Element is an array }
You can determine if an element is a string with this code:
if (Object.prototype.toString.call(MyQueryString['names']) === '[object String]') { // Element is a string }
Version History
1.0 2015.12.06 Tested by Russ Tanner.
Author
Russ Tanner russ@russtanner.com russtanner.com
*/
var r = {};
// Default parameters.
if (def === undefined) { def = null; }
// The query string is not a string or is zero-length. Return an empty object.
if (Object.prototype.toString.call(qs) === '[object String]' && qs.trim() === '') { return r; }
// The query string contains a leading question mark. Remove it.
if (qs.indexOf('?') === 0) { qs = qs.substr(1); }
// Parse each element of the query string.
qs.split('&').forEach(
function(x) {
// Split elements and decode the values.
var s = x.split("="), k = s[0], v = s[1] && decodeURIComponent(s[1]);
// The variable has no value. Assign it the specified default value.
// The value is undefined if "?example". The value is a zero-length string ("") if "?example=".
if (v === undefined || v.trim() === '') { v = def; }
// Place the element on the return buffer object.
(k in r) ? ((Object.prototype.toString.call(r[k]) === '[object Array]') ? r[k].push(v) : r[k] = [r[k], v]) : r[k] = v;
}
)
return r;
}
|
|
|
|
Entire Thread
|
QueryString_ToObj(QueryString)
|
Russ
|
12/07/15 01:36 AM
|
|
|
|