Skip to content

Instantly share code, notes, and snippets.

@rosschapman
Last active July 15, 2020 19:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rosschapman/9f607c2e5e7f964861b41f9cc3d9d075 to your computer and use it in GitHub Desktop.
Save rosschapman/9f607c2e5e7f964861b41f9cc3d9d075 to your computer and use it in GitHub Desktop.
Extract Host and TLD from valid url
// 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