Skip to content

Instantly share code, notes, and snippets.

@jdmallen
Last active April 16, 2018 18:28
Show Gist options
  • Select an option

  • Save jdmallen/7086f7dfbae05bae5da20da3a809dd80 to your computer and use it in GitHub Desktop.

Select an option

Save jdmallen/7086f7dfbae05bae5da20da3a809dd80 to your computer and use it in GitHub Desktop.
Regex pattern to capture the domain and params of a URL
// Regex:
// /(?:https?:\/\/)?(?:www\.)?([-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6})(?:[:]?[0-9]{0,5})([-a-zA-Z0-9@:%_\+.~#?&\/=]*)/i
function extractUrlParts(url) {
var matches =
/(?:https?:\/\/)?(?:www\.)?([-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6})(?:[:]?[0-9]{0,5})([-a-zA-Z0-9@:%_\+.~#?&\/=]*)/i
.exec(url);
return {
domain: matches && matches[1],
params: matches && matches[2]
}
}
var testUrls = [
"/Relative/Path",
"http://www.youtube.com/watch?v=lXMskKTw3Bc",
"https://www.youtube.com/watch?v=lXMskKTw3Bc",
"www.youtube.com/watch?v=lXMskKTw3Bc",
"ftps://ftp.place.com/dir/file.txt",
"ftps://place.com:1234/dir/file.txt",
"place.com:1234/dir/file.txt",
"https://jdmallen.github.io/jest/"
];
for (var i = 0; i < testUrls.length; i++){
document.write("<h4>URL: "
+ testUrls[i] + "</h4><b>Domain: </b>"
+ extractUrlParts(testUrls[i]).domain + "<br/><b>Params: </b>"
+ extractUrlParts(testUrls[i]).params);
}
@jdmallen

Copy link
Copy Markdown
Author

jsbin to test the above

@jdmallen

jdmallen commented Apr 16, 2018

Copy link
Copy Markdown
Author

Work largely based on this StackOverflow answer. The RegEx was changed to include port numbers and change the capture groups.

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