Explain Codes LogoExplain Codes Logo

How to replace plain URLs with links?

javascript
linkification
url-parsing
regex
Anton ShumikhinbyAnton Shumikhin·Oct 4, 2024
TLDR
// Good old faithful regex to the rescue const linkify = text => text.replace(/\b(http:\/\/|https:\/\/\S+)/gi, '<a href="$&" target="_blank">$&</a>'); // Now, let's see this baby in action console.log(linkify('Visit http://example.com')); // "Visit <a href="http://example.com" target="_blank">http://example.com</a>"

Marvel at the simplicity of the .replace() method, coupled with a URL-matching regex, converting http:// or https:// URLs tucked inside the text into <a> links faster than you can spell "JavaScript".

Cracking the URL nut using libraries

For more reliable results, consider existing URL parsing libraries. They come in handy handling edge cases like international domain names, TLDs, punctuation, and IPV6 hostnames. Take a look at some champions in this arena: linkify, AnchorMe, Autolinker.js.

linkify - not your grandma's library

Linkify turns URLs and emails into links and does a fantastic job avoiding double-linking.

var linkifiedText = linkify('email to: [email protected]. Visit: http://example.com');

AnchorMe.js - throw off those training wheels

Though more experimental, AnchorMe converts URLs and emails into clickable links, holding your hand less than linkify.

var anchoredText = anchorme('Visit me at https://portfolio.me and drop an email');

Autolinker.js - Marvel's new Avenger

Autolinker.js is like a Swiss Army knife – it links URLs, emails, phone numbers, hashtags, and mentions. Plus, you can customize it.

var autoLinkedText = Autolinker.link('Visit me at http://homepage.com and don't forget to #like and #follow');

Linkification: One step beyond

Don't discriminate URLs

Whether it's http, https, ftp, file, or the classic "www" prefix, all URLs deserve to be linkified:

const linkifyAll = text => text.replace(/(?:https?|ftp):\/\/[\n\S]+/g, '<a href="$&">$&</a>');

Double-linking is a no no

Steer clear of double-linking by checking if the URL is already part of an anchor tag:

const avoidDoubleLinking = text => text.replace(/(href=")?(https?:\/\/\S+)/gi, (match, capture) => capture ? match : `<a href="${match}">${match}</a>`);

Real-time text, serious considerations

Optimize your code and handle text with care. When replacing URLs in real-time text processing or when dealing with dynamically generated content, efficiency matters:

// Our regex ninja is about to make a move! Watch out... const safeLinkify = text => { const urlRegex = /.../; // Your complex, trend-setting regex let matchArray; while ((matchArray = urlRegex.exec(text)) !== null) { let match = matchArray[0]; // Cue Mission Impossible theme music, time for some secret operations } return text; // And text lived happily ever after, with links! };