safeHref

tcmts.share.safeHref · #vmqtlu7v · term · runs anywhere

A link's address, if it's one a page may link to: http, https or mailto, or one with no scheme (a path, #…). Others (javascript:, data:, vbscript:…) are undefined, read as a browser reads them (it skips tabs, newlines and leading spaces and control characters, so java\tscript: is javascript:).

export function safeHref(href: string): string | undefined {
  // eslint-disable-next-line no-control-regex
  const read = href.replace(/[\u0000- \u007f]/g, "");
  const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(read)?.[1]?.toLowerCase();
  return scheme === undefined || scheme === "http" || scheme === "https" || scheme === "mailto"
    ? href
    : undefined;
}

used by