AngularJS filter to make urls in text clickable

28 Jun 2019

angularjs js

Repost from this article

This is a simple filter I made for Angular.JS to make url’s in text clickable. Make sure you place the content and filter in the ng-bind-html attribute of the HTML element. Otherwise the HTML won’t be parsed.

E.g. <p ng-bind-html="comment.body | parseUrl"></p>

Here’s the parseUrl filter:

angular
    .module('filters', [])
    .filter('parseUrl', function() {
        var urls = /(\b(https?|ftp):\/\/[A-Z0-9+&@#\/%?=~_|!:,.;-]*[-A-Z0-9+&@#\/%=~_|])/gim;
        var emails = /(\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})/gim;

        return function(text) {
            if(text.match(urls)) {
                text = text.replace(urls, "<a href=\"$1\" target=\"_blank\">$1</a>");
            }
            if(text.match(emails)) {
                text = text.replace(emails, "<a href=\"mailto:$1\">$1</a>");
            }

            return text;
        }
    });

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.