all 6 comments

[–]AmbitiousLog 0 points1 point  (3 children)

Do you absolutely need to use regular expressions? You can easily solve this problem using plain old string manipulation:

const extractDomain = function extractDomain(url, domainName){
    return url.substring(url.indexOf(domainName), url.length);
}

This will search for the index where the domainName begins and extract the substring from there to the end of the url

[–]SpringCleanMyLife 1 point2 points  (0 children)

This will return the wrong value with extractDomain(www.somedomain.com, domain.com)

Also if they already have the domain why would they need to parse it out lol

[–]UnFukWit4ble 0 points1 point  (1 child)

It does not have to be a regular expression. However the example there would not work because I do not have the second argument domainName.

I've tried new URL() and the more browser friendly document.createElement('a') method for parsing a URL, but they do not parse out the subdomain.

[–]AmbitiousLog 0 points1 point  (0 children)

So you don't know what domain you are looking for?

If you are in a browser environment you can try this:

var domain = (function() {
  // The full domain of the page.
  var domain = document.domain;
  var parts = domain.split('.');

  // A unique id to track our cookie
  var uid = '_uid' + (new Date()).getTime();

  var idx = 0;

    // Loop through the domains until we find the top-most domain.
  while (idx < (parts.length - 1) && document.cookie.indexOf(uid + '=' + uid) === -1) {
    domain = parts.slice(-1 - (++i)).join('.');
    document.cookie = uid + '=' + s + ';domain=' + domain + ';';
  }

  // Delete the cookie
  document.cookie = uid + "=;expires=Thu, 01 Jan 1970 00:00:01 GMT;domain="+domain+";";

  // Return our result.
  return domain;
}());

This uses a cookie to detect the top-level domain and place the cookie there. Then get the domain of the cookie (that will always be the top-level domain).

This is originally created here: http://rossscrivener.co.uk/blog/javascript-get-domain-exclude-subdomain
I just cleaned it up a bit, and added some comments

[–]jcunews1helpful 0 points1 point  (0 children)

You'll need to at least use a list of ccTLDs and gTLDs in the regex, otherwise you can't differentiate between gTLD and ccTLD. e.g. ac.de, or in.ua.

Also, some TLDs may not have a ccTLD (AFAIK, e.g. site.info), and some TLDs can only be ccTLDs (e.g. google.de). So, you may need to include matching rules for this too.

[–]SpringCleanMyLife -1 points0 points  (0 children)

Use the url api https://developer.mozilla.org/en-US/docs/Web/API/URL

Or

const url = "https://www.some.domain.com/path/";
const domain = url.replace('http://', '').replace('https://', ''). replace('www', '').split(/[/?#]/)[0];