Angularjs directive to replace text

前端 未结 6 661
陌清茗
陌清茗 2020-12-04 18:05

How would I create a directive in angularjs that for example takes this element:

Example text http://example.com

And

6条回答
  •  醉梦人生
    2020-12-04 18:49

    Inspired by @Neal I made this "no sanitize" filter from the newer Angular 1.5.8. It also recognizes addresses without ftp|http(s) but starting with www. This means that both https://google.com and www.google.com will be linkyfied.

    angular.module('filter.parselinks',[])
    
    .filter('parseLinks', ParseLinks);
    
    function ParseLinks() {
      var LINKY_URL_REGEXP =
            /((ftp|https?):\/\/|(www\.)|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>"\u201d\u2019]/i,
          MAILTO_REGEXP = /^mailto:/i;
    
      var isDefined = angular.isDefined;
      var isFunction = angular.isFunction;
      var isObject = angular.isObject;
      var isString = angular.isString;
    
      return function(text, target, attributes) {
        if (text == null || text === '') return text;
        if (typeof text !== 'string') return text;
    
        var attributesFn =
          isFunction(attributes) ? attributes :
          isObject(attributes) ? function getAttributesObject() {return attributes;} :
          function getEmptyAttributesObject() {return {};};
    
        var match;
        var raw = text;
        var html = [];
        var url;
        var i;
        while ((match = raw.match(LINKY_URL_REGEXP))) {
          // We can not end in these as they are sometimes found at the end of the sentence
          url = match[0];
          // if we did not match ftp/http/www/mailto then assume mailto
          if (!match[2] && !match[4]) {
            url = (match[3] ? 'http://' : 'mailto:') + url;
          }
          i = match.index;
          addText(raw.substr(0, i));
          addLink(url, match[0].replace(MAILTO_REGEXP, ''));
          raw = raw.substring(i + match[0].length);
        }
        addText(raw);
        return html.join('');
    
        function addText(text) {
          if (!text) {
            return;
          }
          html.push(text);
        }
    
        function addLink(url, text) {
          var key, linkAttributes = attributesFn(url);
          html.push('');
          addText(text);
          html.push('');
        }
      };
    }
    

提交回复
热议问题