2

Extract domain extension (e.g. .com) NOT the domain name (e.g. google.com) from hostname using regex.

input => output

www.google.com => .com

google.com => .com

google.co.uk => .co.uk

www.google.co.uk => .co.uk

sub.google.co.uk => .co.uk

NOT a duplicate of Get domain name without subdomains using JavaScript?

Steve
  • 4,946
  • 12
  • 45
  • 62
  • the answer you link to actually will help you ... `psl(somedomain).tld` is what you want ... the `tld` is misleading but is what you want – Jaromanda X Sep 29 '19 at 01:43

2 Answers2

2

You can manually check for the list of country domains and then the preceding domain segment that appears before it.

That is: <other>.<topLevelDomain>.[optionalCountryCode]

Example below:

function getTopDomain(domain) {
  const topDomainExpression = /\w+((\.[a-z]{2,3})(\.(ad|ae|af|ag|ai|al|am|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bl|bm|bn|bo|bq|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cw|cx|cy|cz|de|dj|dk|dm|do|dz|ec|ee|eg|er|es|et|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mf|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|ss|st|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|za|zm|zw))?)$/i;
  const match = topDomainExpression.exec(domain);
  
  return match[1];
}

function test(input, expectedOutput) {
  const output = getTopDomain(input);
  console.log(`${output === expectedOutput ? 'PASS' : 'FAIL'}: ${input} (expected: ${expectedOutput}, output: ${output})`);
}

test('www.google.com', '.com');
test('google.com', '.com');
test('google.co.uk', '.co.uk');
test('www.google.co.uk', '.co.uk');
test('sub.google.co.uk', '.co.uk');
test('bit.ly', '.ly');
test('something.co.ly', '.co.ly');
Soc
  • 7,425
  • 4
  • 13
  • 30
-1

Try this:

function getExtension(hostname){ let e = hostname.slice(hostname.search('.'), hostname.length); return e; }

chambers
  • 1
  • 1