Javascript正则表达式打破选择正斜杠

时间:2014-07-29 19:29:58

标签: javascript regex angularjs

使用正则表达式将@something#something链接到字符串中。在这两种情况下,它都能正常工作。尝试使用相同的方法链接/something,但它会破坏所有内容。

适用于@# http://jsbin.com/todomuca/3/edit

由于链接44,

不适用于/http://jsbin.com/todomuca/4/edit

知道它为什么会破裂吗?

<!DOCTYPE html>
<html ng-app="app">
<head>
<title>Title</title>
</head>
<body>

<p linkify="twitter">some @username and #hashtag and now trying /test</p>

<!-- javascript -->
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
<script>

angular.module('linkify', []);

angular.module('linkify')
  .filter('linkify', function () {
      'use strict';

      function linkify (_str, type) {
        if (!_str) {
          return;
        }

        var _text = _str.replace( /(?:https?\:\/\/|www\.)+(?![^\s]*?")([\w.,@?^=%&amp;:\/~+#-]*[\w@?^=%&amp;\/~+#-])?/ig, function(url) { 
            var wrap = document.createElement('div');
            var anch = document.createElement('a');
            anch.href = url;
            anch.target = "_blank";
            anch.innerHTML = url;
            wrap.appendChild(anch);
            return wrap.innerHTML;
        });

        // bugfix
        if (!_text) {
          return '';
        }

        // Twitter
        if (type === 'twitter') {
          _text = _text.replace(/(|\s)*@(\w+)/g, '$1<a href="https://twitter.com/$2" target="_blank">@$2</a>');
          _text = _text.replace(/(^|\s)*#(\w+)/g, '$1<a href="https://twitter.com/search?q=%23$2" target="_blank">#$2</a>');
          _text = _text.replace(/(^|\s)*\/(\w+)/g, '$1<a href="https://twitter.com/search?q=$2" target="_blank">#$2</a>');
        }

        // Github
        if (type === 'github') {
          _text = _text.replace(/(|\s)*@(\w+)/g, '$1<a href="https://github.com/$2" target="_blank">@$2</a>');
        }

        return _text;
      }

      //
      return function (text, type) {
        return linkify(text, type);
      };
  })
  .factory('linkify', ['$filter', function ($filter) {
    'use strict';

    function _linkifyAsType (type) {
      return function (str) {(type, str);
        return $filter('linkify')(str, type);
      };
    }

    return {
      twitter: _linkifyAsType('twitter'),
      github: _linkifyAsType('github'),
      normal: _linkifyAsType()
    };
  }])
  .directive('linkify', ['$filter', '$timeout', 'linkify', function ($filter, $timeout, linkify) {
    'use strict';

    return {
      restrict: 'A',
      link: function (scope, element, attrs) {
        var type = attrs.linkify || 'normal';
        $timeout(function () { element.html(linkify[type](element.html())); });
      }
    };
  }]);


var app = angular.module("app", ['linkify']);

</script>
</body>
</html>

1 个答案:

答案 0 :(得分:3)

您正在对原始HTML运行替换,在早期替换之后,它包含</a>,它与您的/匹配的正则表达式匹配。您可以尝试同时匹配它们:

var TWITTER_LINK = /(?:^|\s)([@#/])(\w+)/g;

var html = text.replace(TWITTER_LINK, function (match, type, name) {
    var url = {
        '@': 'https://twitter.com/' + name,
        '#': 'https://twitter.com/search?q=%23' + name,
        '/': 'https://twitter.com/search?q=' + name
    }[type];

    return '<a href="' + url + '">' + match + '</a>';
});
但是,那仍然不是很愉快;我会使用DOM。

var TWITTER_LINK = /(?:^|\s)([@#/])(\w+)/g;
var result = document.createDocumentFragment();
var lastIndex = 0;
var match;

while ((match = TWITTER_LINK.exec(text)) {
    result.appendChild(document.createTextNode(text.substring(lastIndex, match.index)));
    lastIndex = match.index;

    var type = match[1];
    var name = match[2];

    var url = {
        '@': 'https://twitter.com/' + encodeURIComponent(name),
        '#': 'https://twitter.com/search?q=%23' + encodeURIComponent(name),
        '/': 'https://twitter.com/search?q=' + encodeURIComponent(name)
    }[type];

    var link = document.createElement('a');
    link.href = url;
    link.appendChild(document.createTextNode(match[0]));
    result.appendChild(link);
}

result.appendChild(document.createTextNode(text.substring(lastIndex)));