Skip to content

Instantly share code, notes, and snippets.

@szepeviktor
Last active May 10, 2020 08:53
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save szepeviktor/8283110 to your computer and use it in GitHub Desktop.
Save szepeviktor/8283110 to your computer and use it in GitHub Desktop.
parseUri 1.2.2 Author: Steven Levithan URL: http://blog.stevenlevithan.com/archives/parseuri
// parseUri 1.2.2
// (c) Steven Levithan <stevenlevithan.com>
// MIT License
function parseUri (str) {
var o = {
strictMode: false,
key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
q: {
name: "queryKey",
parser: /(?:^|&)([^&=]*)=?([^&]*)/g
},
parser: {
strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
}
},
m = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
uri = {},
i = 14;
while (i--) uri[o.key[i]] = m[i] || "";
uri[o.q.name] = {};
uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
if ($1) uri[o.q.name][$1] = $2;
});
return uri;
};
// without query string parser: https://gist.github.com/jlong/2428561
@SeanBannister
Copy link

SeanBannister commented May 10, 2020

I've been using this for years but recently found out there's now a URL parser in the javascript spec:
https://developer.mozilla.org/en-US/docs/Web/API/URL

@szepeviktor
Copy link
Author

Thank you!

var url = new URL("http://www.example.com/cats#tabby");
for (part in url) { console.log(part, url[part]); }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment