user3710846 user3710846 - 9 days ago 6
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="http://somepage.com?number=$&">$&</a>') + " | ";
};
});


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

Like
E12345-01
does not become
somepage.com?number=E12345-01


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

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="http://somepage.com?number=$&">$&</a>') + ' | ');
    };
  });

Here is an example plnk of the code working.

Comments