Autolinker.js

4.1.5 · active · verified Sun Apr 19

Autolinker.js is a robust JavaScript utility designed to automatically detect and convert various patterns like URLs, email addresses, phone numbers, and social media mentions/hashtags (Twitter, Instagram, YouTube, TikTok, Facebook, Soundcloud) within plain text or HTML into clickable hyperlinks. The current stable version is `v4.1.5`. The library maintains an active release cadence, frequently publishing minor and patch updates, often focusing on performance enhancements and bug fixes. A key differentiator is its rewritten URL parser in `v4.0.0`, which utilizes a finite state machine for `O(n)` linear time performance, significantly improving speed and preventing 'catastrophic backtracking' issues common with regular expression-based parsers. Unlike many alternatives, Autolinker.js is meticulously designed to correctly handle HTML input, avoiding the creation of nested anchor tags or inadvertently modifying existing `href` attributes, making it particularly suitable for processing rich text content where correctness and performance are critical.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize Autolinker with various options and link a block of text, including a custom `replaceFn` to modify the generated anchor tags.

import Autolinker from 'autolinker';

const inputText: string = "Check out my website at example.com, email me at test@example.org, or call me at +1 (123) 456-7890. Also, find me on Twitter @myhandle and hashtag #myproject.";

const autolinker = new Autolinker({
  urls: { scheme: true, www: true, ipV4Matches: true },
  email: true,
  phone: true,
  mention: 'twitter',
  hashtag: 'twitter',
  newWindow: true,
  stripPrefix: false,
  // Custom replace function to add specific classes or attributes
  replaceFn: (match) => {
    const tag = match.buildTag();
    if (match.getType() === 'url') {
      tag.setAttr('class', 'my-url-link');
    }
    return tag;
  }
});

const linkedText: string = autolinker.link(inputText);

console.log(linkedText);
// Expected output: Check out my website at <a href="http://example.com" class="my-url-link" target="_blank" rel="noopener noreferrer">example.com</a>, email me at <a href="mailto:test@example.org" target="_blank" rel="noopener noreferrer">test@example.org</a>, or call me at <a href="tel:+11234567890" target="_blank" rel="noopener noreferrer">+1 (123) 456-7890</a>. Also, find me on Twitter <a href="https://twitter.com/myhandle" target="_blank" rel="noopener noreferrer">@myhandle</a> and hashtag <a href="https://twitter.com/hashtag/myproject" target="_blank" rel="noopener noreferrer">#myproject</a>.

view raw JSON →