AngularJS Linkify Filter
An AngularJS filter (written in CoffeeScript) to find a url in a string and replace it with an anchor tag.
Background
A current client project I am working on allows administrative users to enter dynamic tips to be displayed to users. These tips can contain links, however, they are just plain text in the DB. The client wants these tips to be linkable. One approach would be to update the strings in the DB (migration) to contain the anchor tags. While this approach works for current tips, it is undesirable because it would force admins to use html when creating new tips in the future. AngularJS Filters to the rescue.
The Filter
The filter defines a URL Regex. If a valid input string is provided the JavaScript replace function is invoked on it. Using the function argument option to the replace call and JavaScript arguments, we can create a valid anchor tag and update the input string.
angular.module('myApp')
.filter 'linkify', () ->
(input) ->
if input
urlRegex = /(^|\s)((https?:\/\/)?[\w-]+(\.[\w-]+)+\.?(:\d+)?(\/\S*)?)/gi
input.replace urlRegex, ->
uri = arguments[2]
uri = "http://#{uri}" if arguments[3] is undefined
" <a href=\"#{uri}\" target=\"_blank\">#{arguments[0]}</a>"
Usage
The filter can be applied from both html views and JS code via AngularJS filter sytanx
Views
<div ng-repeat="tip in tips">
<p ng-bind-html="tip | linkify"></p>
</div>
JS
linkifyFilter = $filter('linkify');
// single string
linkifiedString = linkifyFilter(stringToLinkify);
// array of strings
filteredStrings = stringsToFilter.map(function (stf) {
return linkifyFilter(stf);
});
Written by Louis Sivillo
Related protips
1 Response
Great for CMS.