Skip to content

Instantly share code, notes, and snippets.

@ttonyh
Created December 1, 2016 23:42
Show Gist options
  • Save ttonyh/64264f9f6bd4c75d8734de494c2effcc to your computer and use it in GitHub Desktop.
Save ttonyh/64264f9f6bd4c75d8734de494c2effcc to your computer and use it in GitHub Desktop.
Simple Parse Uri function using HTMLAnchorElement
var uriNames = 'protocol hostname host pathname port search hash href origin'.split( ' ' );
var parseUri = function( url ) {
var Uri = function uri() {
var self = this,
setProp = function( nm, val ) {
if ( nm === 'search' ) {
val = ( String( val )[ 0 ] !== '?' ) ? '?' + val : val;
}
return self.a[ nm ] = val;
};
self.a = doc.createElement( 'a' );
self.a.href = url;
uriNames.forEach( function( nm ) {
var _p = self.a[ nm ];
Object.defineProperty( self, nm, {
get: function() { return _p; },
set: function( val ) { _p = setProp( nm, val ); }
});
});
};
Uri.prototype.toUrlString = function() {
return this.a.href;
};
return new Uri();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment