Automatic text linking

React, Components, Fragment, Regexp · Nov 3, 2020

Renders a string as plaintext, with URLs converted to appropriate link elements.

  • Use String.prototype.split() and String.prototype.match() with a regular expression to find URLs in a string.
  • Return matched URLs rendered as <a> elements, dealing with missing protocol prefixes if necessary.
  • Render the rest of the string as plaintext.
const AutoLink = ({ text }) => {
  const delimiter = /((?:https?:\/\/)?(?:(?:[a-z0-9]?(?:[a-z0-9\-]{1,61}[a-z0-9])?\.[^\.|\s])+[a-z\.]*[a-z]+|(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3})(?::\d{1,5})*[a-z0-9.,_\/~#&=;%+?\-\\(\\)]*)/gi;

  return (
    <>
      {text.split(delimiter).map(word => {
        const match = word.match(delimiter);
        if (match) {
          const url = match[0];
          return (
            <a href={url.startsWith('http') ? url : `http://${url}`}>{url}</a>
          );
        }
        return word;
      })}
    </>
  );
};
ReactDOM.render(
  <AutoLink text="foo bar baz http://example.org bar" />,
  document.getElementById('root')
);

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub or Twitter.

More like this

  • Uncontrolled textarea element

    Renders an uncontrolled <textarea> element that uses a callback function to pass its value to the parent component.

    React, Components · Nov 25, 2020

  • Textarea with word limit

    Renders a textarea component with a word limit.

    React, Components · Oct 13, 2021

  • Collapsible accordion

    Renders an accordion menu with multiple collapsible content elements.

    React, Components · Oct 13, 2021