0

我有通过 Twitter API 生成的推文,例如:

<article class="tweet">
    Some users may have experienced issues accessing http://t.co/zDdcbPNfnU on @Firefox 22+. We've reached out to Mozilla and it's now resolved.
</article>
<article class="tweet">
  The issue with viewing photos is now resolved. Thanks for your patience!
</article>

链接没有使用正确的标记生成,所以现在我要做的是选择任何以开头http://的单词并将这些单词包装在锚标记中。

我以为我可以做类似的事情,但这显然行不通:

$('article.tweet').each(function(){
  var linkHref = $(this).html().find('http://');
  $(linkHref).wrap('<a href="' + linkHref + '" />');
});

如何使用 jQuery 选择链接?

4

1 回答 1

2

您可以尝试用 RegExp 替换它:

$('article.tweet').each(function(){
  var linkHref = $(this).html().replace(/http:\/\/\S+/g, function (match) {
     return "<a href='" + match + "'>" + match + "</a>"
  });
  $(this).html(linkHref);
});

在 的第二个参数中提供一个函数replace()来格式化每个匹配的 URL。

小提琴示例

于 2013-09-17T11:52:50.497 回答