Skip to content

isExternal

Whether a link points to another origin than base: an absolute http(s) URL or a protocol-relative one (//host/path). Paths, anchors, query strings and non-HTTP schemes (mailto:, tel:) are never external.

Without base, any absolute or protocol-relative URL counts as external. With a base, a link to the same origin is internal: same scheme, host and port, the default port of the scheme (80 for http, 443 for https) being the same as no port. A base with no scheme and host, or a link with no host, gives false.

It reads the origin from the text and uses no URL global, so it runs on every runtime. A real URL is accepted as base, as is any object with an href.

Available since v3.1.4

import { isExternal } from '@helpers4/url';
// or, from the all-in-one package (same code, one install):
import { isExternal } from 'helpers4/url';
isExternal(url: string, base?: string | object): boolean
ParameterTypeDescription
urlstringThe link to check
basestring | objectThe current origin or page URL to compare with (optional) (optional)

boolean — true if the link leaves the origin, false otherwise

Compares the link with the current origin: same-origin absolute links stay internal.

isExternal('https://github.com/helpers4', 'https://helpers4.dev')
// => true
isExternal('https://helpers4.dev/docs', 'https://helpers4.dev')
// => false

Relative paths, anchors, mailto: and tel: are never external; protocol-relative URLs are.

isExternal('/docs')                 // => false
isExternal('mailto:hi@example.com') // => false
isExternal('//cdn.example.com/a.js') // => true

View source on GitHub