Last active
April 16, 2018 18:28
-
-
Save jdmallen/7086f7dfbae05bae5da20da3a809dd80 to your computer and use it in GitHub Desktop.
Regex pattern to capture the domain and params of a URL
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
| // 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); | |
| } |
Author
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
jsbin to test the above