Last active
June 29, 2017 09:32
-
-
Save DJDaveMark/b2bd1045c03baccee6f744b8eb23d99d to your computer and use it in GitHub Desktop.
JavaScript class for parsing location.search query attributes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Use to parse location.search query attributes. | |
* Example usage: | |
* var query = new QueryValues(location.search); // "?id=124875&foo=bar&foo=baz" | |
* var id = query.attr("id"); // "124875" | |
* var foos = query.attrs("foo"); // ["bar", "baz"] | |
*/ | |
var QueryValues = (function () { | |
var LIMIT = 2; | |
var QueryValues = function (search) { | |
this.attrs = {}; | |
if (search == null || search === "") { | |
return; | |
} | |
search = search.trim(); | |
if (search.indexOf("?") == 0) { | |
search = search.substr(1); | |
} | |
var pairs = search.split("&"); | |
pairs.forEach(function (pair) { | |
var parts = pair.split('=', LIMIT); | |
var value = parts.length >= LIMIT ? parts[1] : null; | |
this.addAttr(parts[0], value); | |
}, this); | |
}; | |
QueryValues.prototype.addAttr = function (name, value) { | |
if (name == null || name === "") { | |
return; | |
} | |
if (value != null) { | |
value = decodeURIComponent(value.replace(/\+/g, " ")); | |
} | |
if (this.hasAttr(name)) { | |
this.attrs[name].push(value); | |
} else { | |
this.attrs[name] = [value]; | |
} | |
}; | |
QueryValues.prototype.hasAttr = function (name) { | |
return this.attrs.hasOwnProperty(name); | |
}; | |
QueryValues.prototype.attr = function (name) { | |
var attr; | |
if (this.hasAttr(name)) { | |
attr = this.attrs[name][0]; | |
} | |
return attr; | |
}; | |
QueryValues.prototype.attrs = function (name) { | |
var attrs; | |
if (this.hasAttr(name)) { | |
attrs = this.attrs.slice(); | |
} | |
return attrs; | |
}; | |
return QueryValues; | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment