• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 3548
  • Last Modified:

get subdomain of url

Hi,

I wish to grab the subdomain portion of a url using javascript. I have this client's url:
http://medicaid-florida.medicaidconsultants.com/

I want to grab only the portion 'medicaid-florida' and save it to a variable.

Is there an easy way to do this?

Thank you,
vkimura
0
Victor Kimura
Asked:
Victor Kimura
  • 3
  • 2
  • 2
  • +1
5 Solutions
 
sam2912Commented:

var subdomain=window.location.href.split("/")[2].split(".")[0];
alert(subdomain);

Open in new window

0
 
sam2912Commented:
The code below is if you already have the URL stored in a variable
var domain = "http://medicaid-florida.medicaidconsultants.com/";
var subdomain = domain.split("/")[2].split(".")[0];
alert(subdomain);

Open in new window

0
 
govindarajan78Commented:
another method:
var subdomain=document.location.href.replace("http://","").replace(".medicaidconsultants.com/","")

but if you have page name and querystrings then then this code will fail.
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
halfbloodprinceCommented:
THIS WORKS!!!!:
function getSubDomain()
        {
            var str = "http://medicaid-florida.medicaidconsultants.com/"
            var arrValue = str.split("//");
            var arrSecondValue = arrValue[1].split(".");

            alert(arrSecondValue[0]);

        }
0
 
halfbloodprinceCommented:
THIS WORKS!!!!:
function getSubDomain()
        {
            var str = "http://medicaid-florida.medicaidconsultants.com/"
            var arrValue = str.split("//");
            var arrSecondValue = arrValue[1].split(".");
            var result = arrSecondValue[0];
            alert(result);

        }
0
 
govindarajan78Commented:
instead of
window. location.href
use
window.location.host
0
 
Victor KimuraSEO, Web DeveloperAuthor Commented:
Hi govindarajan78,

What's the difference between the two?
0
 
govindarajan78Commented:
the location.host will omit the file names & querystrings if any
0

Featured Post

2018 Annual Membership Survey

Here at Experts Exchange, we strive to give members the best experience. Help us improve the site by taking this survey today! (Bonus: Be entered to win a great tech prize for participating!)

  • 3
  • 2
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now