2

Is there a way to get a domain without any subdomain from an url with javascript? I tried some approaches, but all of them deliver domain with subdomain.

All regular expressions i was seeing were able just to filter www out - other subdomains were on their place.

Maybe somebody knows a javascript hint, like this one in Java.

Possible input: https://us.www.example.com/folder-1/index.html

Desired output: example.com

To go more in detail: i'm working on a Chrome extension and want to pass a domain from background.js to popup.js. I get current url, and then the domain from the current url with:

chrome.tabs.onUpdated.addListener(function(tabid, changeInfo, tab){
    chrome.tabs.query({'active' : true, 'currentWindow': true}, function(tabs){
        let newUrl = new URL(tabs[0].url);
        currentDomain = newUrl.hostname;
});

But - trouble - currentDomain comes with subdomain.

8
  • Can you please edit your question to include an example input and desired output, as well as some code that you've tried? Commented Feb 12, 2020 at 16:30
  • sure, you was just faster then me:) Commented Feb 12, 2020 at 16:33
  • Can you show your research effort? What have you tried to achieve this? Commented Feb 12, 2020 at 16:34
  • new URL("https://us.www.example.com/folder-1/index.html").host gives you the host. Just remove the subdomain. Commented Feb 12, 2020 at 16:36
  • 1
    @R3tep yes, this will be enough. Thank you! Commented Feb 12, 2020 at 16:56

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.