Skip to content

Commit

Permalink
fix: better internal url detection
Browse files Browse the repository at this point in the history
  • Loading branch information
angeloashmore committed Jul 13, 2021
1 parent eaa30e4 commit 10d5dc3
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/lib/isInternalURL.ts
Original file line number Diff line number Diff line change
@@ -1 +1,6 @@
export const isInternalURL = (url: string): boolean => /^\/[^\/]/.test(url);
export const isInternalURL = (url: string): boolean => {
const isInternal = /^(\/(?!\/)|#)/.test(url);
const isSpecialLink = !isInternal && !/^https?:\/\//.test(url);

return isInternal && !isSpecialLink;
};
19 changes: 19 additions & 0 deletions test/lib-isInternalURL.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import test from "ava";

import { isInternalURL } from "../src/lib/isInternalURL";

test("returns true for internal URLs", (t) => {
t.true(isInternalURL("/"));
t.true(isInternalURL("/internal"));
t.true(isInternalURL("#anchor"));
});

test("returns false for external URLs", (t) => {
t.false(isInternalURL("//example.com"));
t.false(isInternalURL("//example.com/image.png"));
t.false(isInternalURL("//example.com#anchor"));
t.false(isInternalURL("https://example.com"));
t.false(isInternalURL("mailto:example.com"));
t.false(isInternalURL("tel:example.com"));
t.false(isInternalURL("ftp:example.com"));
});

0 comments on commit 10d5dc3

Please sign in to comment.