user3710846 user3710846 - 1 year ago 69
AngularJS Question

replace a pattern with URL

The idea is taken from here

I have the following code:

myApp.filter('parseUrlFilter', function () {
var urlPattern = /^E\d{5}-\d{2}$/;
return function (text, target) {
return text.replace(urlPattern, '<a target="' + target + '" href="$&">$&</a>') + " | ";

I'm still trying to understand how this code exactly works but it does not convert the text to URL.

does not become

I think I'm missing something about how the regex works here. Any help will be appreciated.

Edit: added plnkr with somewhat working answer of machinehead115

Answer Source

Without seeing you HTML code I assume that you are actually binding / using the filter there, like so:

<div ng-bind-html="'E12345-01' | parseUrlFilter:'_blank'"></div>

In order to have the filter actually output the link text as code you need to include $sce as a dependency of filter and return the link using $sce.trustAsHtml(link):

angular.module('app', [])
  .filter('parseUrlFilter', function($sce) {
    var urlPattern = /^E\d{5}-\d{2}$/;
    return function(text, target) {
      return $sce.trustAsHtml(text.replace(urlPattern, '<a target="' + target + '" href="$&">$&</a>') + ' | ');

Here is an example plnk of the code working.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download