Last active
December 4, 2019 14:57
-
-
Save cfv1984/372a35db312a853d80261e611dcef1a7 to your computer and use it in GitHub Desktop.
ES6 URI class that can be used with anything resembling an URL.
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
const cache = {}; | |
export default class URI | |
{ | |
constructor(url){ | |
this.url = url | |
this.parts = {} | |
} | |
parse(){ | |
if(this.url in cache){ | |
this.parts = cache[this.url] | |
} | |
else{ | |
const parser = /(\w+)(?:\:\/\/)((?:[\w]+\:[\w]+(?:\@)){0,})([\w\.\:]+)(?:\/)([\w]+)?(?:\?)?([\w\=\%\&\-]+)?(?:\#)?([\w]+)?/gm | |
const [,proto, auth, host, path, qs, fragment] = this.url.split(parser) | |
const parts = { | |
proto, auth, host, path, qs, fragment | |
} | |
this.parts = cache[this.url] = parts | |
} | |
return this; | |
} | |
getPart(part){ | |
if(!Object.keys(this.parts).length){ throw new Error("Unparsed URL.") } | |
return this.parts[part] || ""; | |
} | |
get proto(){ | |
return this.getPart("proto") | |
} | |
get auth(){ | |
return this.getPart("auth").slice(0,-1); | |
} | |
get host(){ | |
return this.getPart("host") | |
} | |
get path(){ | |
return this.getPart("path") | |
} | |
get queryString(){ | |
const myQS = this.getPart("qs") | |
const qs = new URLSearchParams(myQS) | |
return [...qs.entries()].reduce((all, [name,value])=>{ | |
all[name] = value | |
return all | |
},{}); | |
} | |
get fragment(){ | |
return this.getPart("fragment"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment