How to Automatically Detect External Links in a Paragraph of Text With JavaScript

Avoid false URL matches in plaintext

Photo by Artem Sapegin on Unsplash

Checking whether a single string a valid URL is a science in itself. The ultimate source for regex validation methods to detect valid URLs, and not in error matching URLs that aren’t really valid, is long and, for a first-time viewer, highly complicated. The same holds true for questions about URL detection on StackOverflow — there’s considerable interest in those questions.

What I’ve not seen explained in detail is an easy-to-implement JavaScript solution on how to take several paragraphs of text, in a user profile description or a message sent between users, for example, and automatically detect all the URLs within that text — especially, when you don’t know whether there are any URLs at all or where in the text they’re placed.

There are good solutions to this problem on some websites but I’m pretty sure there’s no perfect solution anywhere. Here’s the solution we’ve implemented in vue.js as a JavaScript function. It works in over 99% of our cases and, even more importantly, it doesn’t match non-URLs.