如何使此字符串替换代码与"<br/>"标签一起使用?



从这里提出的关于将字符串中的普通文本替换为URL的问题。。。。如果链接文本被<br/>标记包围,我想让它工作。

这是我目前使用的代码,它在一个看起来像超链接的元素中"链接"文本:

function linkify(inputText) {
    var replacedText, replacePattern1, replacePattern2, replacePattern3;
    //URLs starting with http://, https://, or ftp://
    replacePattern1 = /(b(https?|ftp)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|])/gim;
    replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
    //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
    replacePattern2 = /(^|[^/])(www.[S]+(b|$))/gim;
    replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
    return replacedText;
}

当然,问题是,如果链接文本是这样的:

<p>Is this:<br/><br/>http://www.google.com<br/><br/>THE best search engine around?</p>

然后我得到的结果就是这个!

<p>Is this:<a href="http://www.google.com">http://www.google.comTHE</a> best search engine around</p>

因此,两个问题是<br/>标签被完全剥离,以及<br/>标签('THI')之后的文本被视为超链接文本的一部分。

我该如何克服这个小而致命的问题?

我会更多地依赖内置解析功能的浏览器,让浏览器找出什么是有效的HTML等。

像这样的东西应该工作

function linkify(inputText) {
  var dom = new DOMParser(),
      doc = dom.parseFromString('<div id="wrap">'+ inputText +'</div>', 'text/html'),
      ref = doc.getElementById('wrap'),
      reg = /[-a-zA-Z0-9@:%_+.~#?&//=]{2,256}.[a-z]{2,4}b(/[-a-zA-Z0-9@:%_+.~#?&//=]*)?/gi,
      arr = [];
  Array.prototype.forEach.call(ref.querySelectorAll('*'), function(node) {
    Array.prototype.forEach.call(node.childNodes, function(innerNode) {
      if (innerNode.nodeType === 3) arr.push(innerNode);
    });
  });
  arr.forEach(function(node, index) {
    node.nodeValue = node.nodeValue.replace(reg, function(x) {
      var nxtNode = arr[index+1],
          anchor  = doc.createElement('a');
      if (nxtNode && "nodeValue" in nxtNode) {
        anchor.href = x;
        anchor.innerHTML = nxtNode.nodeValue;
        nxtNode.parentNode.removeChild(nxtNode);
        node.parentNode.insertBefore(anchor, node);
        node.parentNode.removeChild(node);
      }
    });
  });
  return ref.innerHTML;
}

将返回

<p>
    <br><br>
    <a href="http://www.google.com">THE best search engine around</a>
    <br><br>
</p>`

保留所有中断,但将其放置在锚之外

FIDDLE

我建议在您的函数中添加另一个替换项,以便执行您的strip:

function linkify(inputText) {
  var replacedText, replacePattern1, replacePattern2, replacePattern3;
  //URLs starting with http://, https://, or ftp://
  replacePattern1 = /(b(https?|ftp)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|])/gim;
  replacedText = inputText.replace(/<br/>/gi, '').replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
  //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
  replacePattern2 = /(^|[^/])(www.[S]+(b|$))/gim;
  replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
  return replacedText;
}

最新更新