Created
March 11, 2020 01:24
-
-
Save johnmurch/318b80d27d41ab64ef80794d969ac537 to your computer and use it in GitHub Desktop.
getHostname & getDomain -- Simple function for parsing
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 getHostName(url) { | |
var match = url.match(/:\/\/(www[0-9]?\.)?(.[^/:]+)/i); | |
if (match != null && match.length > 2 && typeof match[2] === 'string' && match[2].length > 0) { | |
return match[2]; | |
} | |
else { | |
return null; | |
} | |
} | |
// getHostName('http://www.domain.com/folder/index.html') | |
// domain.com | |
// getHostName('http://mail.google.com/folder/page.html') | |
// mail.google.com | |
function getDomain(url) { | |
var hostName = getHostName(url); | |
var domain = hostName; | |
if (hostName != null) { | |
var parts = hostName.split('.').reverse(); | |
if (parts != null && parts.length > 1) { | |
domain = parts[1] + '.' + parts[0]; | |
if (hostName.toLowerCase().indexOf('.co.uk') != -1 && parts.length > 2) { | |
domain = parts[2] + '.' + domain; | |
} | |
} | |
} | |
return domain; | |
} | |
// getDomain('http://www.amazon.com/gp/registry/wishlist/3B513E3J694ZL/?tag=123') | |
// amazon.com | |
// getDomain('https://mail.google.com/folder/page.html') | |
// google.com |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment