Skip to content

Instantly share code, notes, and snippets.

@zaus
Forked from jlong/uri.js
Created October 24, 2012 21:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zaus/3948998 to your computer and use it in GitHub Desktop.
Save zaus/3948998 to your computer and use it in GitHub Desktop.
URI Parsing with Javascript - regex version

See original gist for discussion and links.

Performance Comparison: http://jsperf.com/url-parsing/5

Testing in Chrome 22.0.1229.94 32-bit on Windows Server 2008 R2 / 7 64-bit

Test Ops/sec

Regex

var matches = urlParseRE.exec(url); var hostname1 = matches[11]; var search1 = matches[16];

1,170,537 ±0.43% fastest

Native

parser.href = url; var hostname2 = parser.hostname; var search2 = parser.search;

88,389 ±0.38% 92% slower

Lib With Regex

var parsed3 = UrlParser.get(url); var hostname3 = parsed3.hostname; var search3 = parsed3.search;

1,005,115 ±0.38% 14% slower

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]
};
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment