Last active
August 29, 2015 14:03
-
-
Save apeque/a8faefbe0989d0c29f3c to your computer and use it in GitHub Desktop.
URL & Query String Parser
This file contains hidden or 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
| var URL = function(url){ | |
| this.url = url; | |
| this.parsed = false; | |
| return this; | |
| }; | |
| URL.prototype.queryStrings = function(queryString){ | |
| var qs = queryString.replace('?', '').split('&'), result = {}; | |
| for(var i=0; i<qs.length; i++) { | |
| var item = qs[i].split("="); | |
| if(item[0].length > 0){ | |
| result[item[0]] = item[1]; | |
| } | |
| } | |
| return result; | |
| }; | |
| URL.prototype.get = function(type, key){ | |
| var parse = (this.parsed || this.parse()); | |
| if(parse && parse[type] && parse[type][key]){ | |
| return parse[type][key]; | |
| } else { | |
| return false; | |
| } | |
| }; | |
| URL.prototype.regex = function(pattern){ | |
| var pattern = new RegExp(pattern); | |
| var check = pattern.test(this.url); | |
| if(check){ | |
| return this.url.match(pattern)[1]; | |
| } | |
| return false; | |
| }; | |
| URL.prototype.parse = function(){ | |
| var parse = null, result = null; | |
| if(this.url){ | |
| parse = document.createElement('a'); | |
| parse.href = ((this.url.indexOf("http://") !== -1 || this.url.indexOf("https://") !== -1) ? this.url : "http://" + this.url); | |
| if(parse.host && parse.host.indexOf('.') == -1){ | |
| return false; | |
| } | |
| result = { | |
| protocol: (parse.protocol ? parse.protocol.replace(':','') : false), | |
| path: parse.pathname, | |
| query: this.queryStrings(parse.search), | |
| host: parse.host | |
| }; | |
| this.parsed = result; | |
| return result; | |
| } else { | |
| return false; | |
| } | |
| }; | |
| URL.prototype.match = function(matches, settings){ | |
| var parse = (this.parsed || this.parse()); | |
| for(var k in matches){ | |
| if(typeof matches[k] == "string"){ | |
| if(parse[k] != matches[k]){ | |
| return false; | |
| } | |
| } else if(typeof matches[k] == "object"){ | |
| for(var x in matches[k]){ | |
| if(typeof matches[k][x] === "string" && matches[k][x] == "isSet"){ | |
| if(parse[k][x] == ""){ | |
| return false; | |
| } | |
| } else { | |
| if(parse[k][x] != matches[k][x]){ | |
| return false; | |
| } | |
| } | |
| } | |
| } | |
| } | |
| return true; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment