1

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.

3
  • 1
    not sure I understand the downvote. I could not find an answer for this in stack-overflow. also I provided a working example in python which means I tried to make this work, but couldnt do it in javascript Commented Oct 19, 2021 at 20:10
  • You can use almost the same code in Javascript: jsfiddle.net/kLvrtdzs Commented Oct 19, 2021 at 20:30
  • @Alexandre this fails for google.co.uk Commented Jan 12, 2022 at 8:56

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Javascript's Array.prototype.slice can handle negative "end" index, so you could write just const subdomains = splitURL.slice(0, -2);.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.