I used this rule for getting the only hostname but it isn't working for subdomain more than 2 characters. What should be else if
when return hostname[1]
, I tried but still first if
runs. I'm open for correct regex or alternative solutions.
Works for:
www.google.com => google
en.store.com => store
google.com => google
www2.site.com => site
www.google.com.tr => google
https://www.google.com.tr => google
https://google.com.tr => google
shop.store.com => shop (should be store)
Code
var match = url.match(/:\/\/(www[0-9]?\.|[a-zA-Z]\.)?(.[^/:]+)/i);
if (match != null && match.length > 2 && typeof match[2] === 'string' && match[2].length > 0) {
var hostname = match[2].split(".");
return hostname[0];
}
else {
return null;
}