Created
July 25, 2016 13:29
-
-
Save haxiomic/515687e2b4079904793721698e8869d5 to your computer and use it in GitHub Desktop.
JavaScript URL parsing with regex - fallback for when window.URL isn't available
This file contains hidden or 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
(function(URL, parent){ | |
var initialConstructor = parent.URL; | |
var urlPattern = new RegExp( | |
"^" + | |
//protocol | |
"(?:((?:\\w+):)?/?/?)" + | |
//user:pass | |
"(?:(?:([^:]*)(?::([^@]*))?)?@)?" + | |
//host | |
"(" + | |
//hostname | |
"([^:/?#]+)" + | |
// port | |
"(?:[:](\\d+))?" + | |
")" + | |
//pathname | |
"([/][^?]*)?" + | |
//search | |
"([?][^#]*)?" + | |
//hash | |
"(#[^$]*)?" + | |
"$", "i" | |
); | |
function URL(urlString, base){ | |
initialConstructor.apply(this, arguments); | |
if(base instanceof URL){ | |
urlString = base.href + '/' + urlString; | |
}else if(base){ | |
urlString = base + '/' + urlString; | |
} | |
urlString = urlString.trim(); | |
var urlMatch = urlString.match(urlPattern); | |
if(!urlMatch){ | |
throw new TypeError('Failed to construct \'URL\': Invalid URL'); | |
} | |
//replace matched undefined/null with "" | |
for(var i = 0; i < urlMatch.length; i++){ | |
urlMatch[i] = urlMatch[i] == undefined ? "" : urlMatch[i]; | |
} | |
this.hash = urlMatch[9]; | |
this.host = urlMatch[4]; | |
this.hostname = urlMatch[5]; | |
this.href = urlString; | |
this.origin = urlMatch[1] + '//' + urlMatch[4]; | |
this.username = urlMatch[2]; | |
this.password = urlMatch[3]; | |
this.pathname = urlMatch[7]; | |
this.port = urlMatch[6]; | |
this.protocol = urlMatch[1]; | |
this.search = urlMatch[8]; | |
} | |
parent.URL = URL; | |
URL.prototype = initialConstructor.prototype; | |
URL.createObjectURL = function(){ | |
console.error('URL.createObjectURL() is not supported'); | |
} | |
URL.revokeObjectURL = function(){ | |
console.error('URL.revokeObjectURL() is not supported'); | |
} | |
URL.prototype.toString = function(){ | |
return this.href; | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment