Skip to content

Commit

Permalink
Sort subdomains correctly for 2-char TLDs like '.io'
Browse files Browse the repository at this point in the history
Add a test to ensure this thing stays fixed.
  • Loading branch information
ssorallen committed Feb 27, 2018
1 parent 5cfa913 commit f388090
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
15 changes: 15 additions & 0 deletions app/js/__tests__/extractRootDomain.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import extractRootDomain from '../extractRootDomain';

describe('extractRootDomain', () => {
test('extracts from 2-character TLDs', () => {
expect(extractRootDomain('https://ssorallen.github.io/react-todos/')).toEqual('github.io');
});

test('extracts country code TLDs', () => {
expect(extractRootDomain('https://www.bbc.co.uk/')).toEqual('bbc.co.uk');
});

test('extracts one of those shenanigans TLDs', () => {
expect(extractRootDomain('http://www.diy.guru/')).toEqual('diy.guru');
});
});
3 changes: 2 additions & 1 deletion app/js/extractRootDomain.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import extractHostname from './extractHostname';

// Original code from https://stackoverflow.com/a/23945027/368697.
export default function extractRootDomain(url: string): string {
let domain = extractHostname(url);
const splitArr = domain.split('.');
Expand All @@ -11,7 +12,7 @@ export default function extractRootDomain(url: string): string {
if (arrLen > 2) {
domain = splitArr[arrLen - 2] + '.' + splitArr[arrLen - 1];
//check to see if it's using a Country Code Top Level Domain (ccTLD) (i.e. ".me.uk")
if (splitArr[arrLen - 1].length === 2 && splitArr[arrLen - 1].length === 2) {
if (splitArr[arrLen - 1].length === 2 && splitArr[arrLen - 2].length === 2) {
//this is using a ccTLD
domain = splitArr[arrLen - 3] + '.' + domain;
}
Expand Down

0 comments on commit f388090

Please sign in to comment.