newbie
newbie

Reputation: 1031

Javascript return only the subdomain part of a string url

I have a string that is typically a url (minus the http/www part). Keep in mind this string is returned via an API and not parsed from the browser url.

For eg "xyz.abc.com or "login.xyz.abc.com"

Now I need to parse the string and return only the subdomain so that I get the following:

"xyz" and "login.xyz"

With Python, I can achieve this using the following code:

".".join(String.split(".")[:-2])

I am unable to find the appropriate syntax or equivalent in javascript.

Upvotes: 1

Views: 80

Answers (1)

sjoerddt
sjoerddt

Reputation: 61

If you're sure that the URL will always have a subdomain (it won't be just abc.com, for example), and that the top-level domain will always consist of one part (it won't be co.uk, for example), you could do this with the following JavaScript:

const exampleURL = "login.xyz.abc.com";
const splitURL = exampleURL.split(".");
const subdomains = splitURL.slice(0, splitURL.length - 2); // Remove the domain
const subdomainsString = subdomains.join(".")
console.log(subdomainsString)

However, keep in mind that the conditions I mentioned above are two pretty big ifs: if an URL is returned as example.co.uk, this method would think that example would be the subdomain.

Upvotes: 2

Related Questions