-2

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:

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;
}
tosunkayaG
  • 15
  • 5

3 Answers3

0

It is not necessary a regex solution although it may resolve your problem.

const list = ['www.google.com',
'en.store.com',
'google.com',
'www2.site.com',
'www.google.com.tr',
'https://www.google.com.tr',
'shop.store.com'
];

function getName(url) {
 const parts = url.split('.');
 return  parts[parts.length - (parts.length > 3 ? 3 : 2 )];   
}

list.forEach((item) => {
   console.log(item,getName(item)) ;
});
JMSalazarDev
  • 155
  • 6
  • Nice alternative but `https://website.com.tr/` gets `com`, `https://website.com` gets `https://website`, also there are some not 3 char domain gtlds like `.club` so `https://website.club` gets `https://website` – tosunkayaG May 21 '21 at 08:43
0

I found this Similar post here is the link for the same Link

URL Format: https://order-dev.companyname.com

Regex that helped to get the sub-domain from the above-mentioned URL (?<=\/\/)(.*?)(?=\.)

Nishant S Vispute
  • 713
  • 1
  • 7
  • 21
0

Solved by getting the text just before the TLD like .com

/(\w|-)+(?=(\.(com|net|org|info|coop|int|co|ac|ie|co|ai|eu|ca|icu|top|xyz|tk|cn|ga|cf|nl|us|eu|de|hk|am|tv|bingo|blackfriday|gov|edu|mil|arpa|au|ru)(\.|\/|$)))/g

source

I'm open for better and efficient solutions only using regex.

tosunkayaG
  • 15
  • 5