Knowing whether a link is internal or external is essential for setting rel in HTML a tag. For an external link, noreferrer noopener nofollow is usually recommended. To test a full URL or relative path in JavaScript/TypeScript, we'll be using URL constructor. It's available in both browsers and Node.js.
It's recommended adding at least rel="noopener" to an external HTML anchor with target="_blank" for security reasons.
Base URL is the full URL of your site's root, usually the home page (e.g. https://nocache.org). This is for reconstructing a relative path to full URL.
Static
Set the base URL to a static URL, change https://nocache.org to your own URL:
const base = newURL('https://nocache.org');
JavaScript
Dynamic (Browsers Only)
Set the base URL to the root of the current URL, only works in browsers:
const base = newURL(`${window.location.protocol}//${window.location.host}`);
JavaScript
Create Function
Create a function that takes an url argument, returns boolean for whether the URL is internal: