Roopendra
Roopendra

Reputation: 7776

Best way to extract domain name in Jquery

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

fiddle

Upvotes: 0

Views: 46

Answers (2)

Gareth Bowen
Gareth Bowen

Reputation: 949

If you prefer regex, this works

var subdomain = siteUrl.match(/http:\/\/([^\.]*)/i)[1];

Upvotes: 0

letiagoalves
letiagoalves

Reputation: 11302

Why not this?

var subdomain = siteUrl.split('//')[1].split('.')[0];

Working demo

Upvotes: 3

Related Questions