Last active
July 15, 2020 19:38
-
-
Save rosschapman/9f607c2e5e7f964861b41f9cc3d9d075 to your computer and use it in GitHub Desktop.
Extract Host and TLD from valid url
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Assumes a valid url | |
export function extractHostAndTLD(url) { | |
const reDot = /\./g; | |
const reAfterDot = /\.(.*)$/; | |
const boxedUrl = new URL(url); | |
const host = boxedUrl.host; | |
if (host.match(reDot).length > 1) { | |
// Ignore the inclusive match and only extract the captured group | |
const [_, afterDot] = host.match(reAfterDot); | |
return afterDot; | |
} | |
return host; | |
} | |
// Sample test | |
describe("extractHostAndTLD", () => { | |
it("returns the correct string", () => { | |
expect(extractHostAndTLD("https://hello.world.io/segment1")).toEqual( | |
"world.io" | |
); | |
expect(extractHostAndTLD("https://world.io/segment1")).toEqual("world.io"); | |
expect(extractHostAndTLD("https://hello.world.io")).toEqual("world.io"); | |
expect(extractHostAndTLD("https://world.io")).toEqual("world.io"); | |
}); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment