Skip to content

Instantly share code, notes, and snippets.

@Rplus
Forked from jlong/uri.js
Last active August 29, 2015 14:07
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save Rplus/764136e190d925790bd6 to your computer and use it in GitHub Desktop.
Save Rplus/764136e190d925790bd6 to your computer and use it in GitHub Desktop.
/* fork form https://gist.github.com/jlong/2428561 */
var parser = document.createElement('a');
parser.href = "http://example.com:3000/pathname/?search=test#hash";
parser.protocol; // => "http:"
parser.hostname; // => "example.com"
parser.port; // => "3000"
parser.pathname; // => "/pathname/"
parser.search; // => "?search=test"
parser.hash; // => "#hash"
parser.host; // => "example.com:3000"
// source: http://jsperf.com/url-parsing/5
// via: https://gist.github.com/jlong/2428561#comment-589710
var url = "http://jblas:password@mycompany.com:8080/mail/inbox?msg=1234&type=unread#msg-content";
var UrlParser = {
regx: /^(((([^:\/#\?]+:)?(?:(\/\/)((?:(([^:@\/#\?]+)(?:\:([^:@\/#\?]+))?)@)?(([^:\/#\?\]\[]+|\[[^\/\]@#?]+\])(?:\:([0-9]+))?))?)?)?((\/?(?:[^\/\?#]+\/+)*)([^\?#]*)))?(\?[^#]+)?)(#.*)?/,
get: function(url) {
var matches = this.regx.exec(url);
// map results
return {
href: matches[0],
withoutHash: matches[1],
url: matches[2],
origin: matches[3],
protocol: matches[4],
protocolseparator: matches[5],
credhost: matches[6],
cred: matches[7],
user: matches[8],
pass: matches[9],
host: matches[10],
hostname: matches[11],
port: matches[12],
pathname: matches[13],
segment1: matches[14],
segment2: matches[15],
search: matches[16],
hash: matches[17]
};
}
};
// use it
var parsed3 = UrlParser.get(url);
parsed3.hostname; // => "mycompany.com"
parsed3.search; // => "?msg=1234&type=unread"
var url = "http://example.com:3000/pathname/?search=test#hash";
var _a = new URL(url);
_a.protocol; // => "http:"
_a.hostname; // => "example.com"
_a.port; // => "3000"
_a.pathname; // => "/pathname/"
_a.search; // => "?search=test"
_a.hash; // => "#hash"
_a.host; // => "example.com:3000"
// try lookup all property in _a
console.dir(_a);
@Rplus
Copy link
Author

Rplus commented Oct 15, 2014

new URL() has to consider whether browsers is supported.

https://developer.mozilla.org/en-US/docs/Web/API/URL.URL#Browser_compatibility
IE don't support...

@Rplus
Copy link
Author

Rplus commented Oct 15, 2014

also see the preformance test:
http://jsperf.com/url-parsing/25

the action of createElement will let the method be slower


update:

getProperty form a DOM object might cause be slow...

@Rplus
Copy link
Author

Rplus commented Oct 15, 2014

visual regexp chart for the UrlParser.regx:
http://tinyurl.com/luo29x4

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