Reputation: 7776
I have an URL e.g http://test.example.com
I need to extract test
(sub domain of this url.) from this url. This url is dynamic it may change so couldn't match with test
and extract it. I have written block of code it is working for me. Can anyone suggest me better way to achieve this.
var siteUrl = 'http://test.example.com';
var parts = siteUrl.split('.');
var subdomainstr = parts.shift(); // Output 'http://test'
var upperleveldomain = parts.join('.'); // Output 'example.com'
var extractSubDomain = subdomainstr.split('//');
var subdomain = extractSubDomain.slice(1).join('.');
console.log(subdomain); //Output test
Upvotes: 0
Views: 46
Reputation: 949
If you prefer regex, this works
var subdomain = siteUrl.match(/http:\/\/([^\.]*)/i)[1];
Upvotes: 0
Reputation: 11302
Why not this?
var subdomain = siteUrl.split('//')[1].split('.')[0];
Upvotes: 3