javascripturltld

Get the "main" domain name JS


My objective is to get the "main" domain name of the current page in JS. By "main", I mean that all these domains should return the same result, "domain":

As you can see, splitting the query at each period and using a fixed index won't work, as the second and third URLs are of the same length, but the main domain is at different indexes.

Does the browser even recognise a part of the domain as the "main" domain? If so, is there a straight forward way to get it with JS? Are there any libraries that can help me with this?


Solution

  • try psl libraries

    // Parse domain with nested subdomains
    var parsed = psl.parse('a.b.c.d.foo.example');
    console.log(parsed.tld); // 'example'
    console.log(parsed.sld); // 'foo'
    console.log(parsed.domain); // 'foo.example'
    console.log(parsed.subdomain); // 'a.b.c.d'