0

I have tweets being generated through the Twitter API, for example:

<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>

The links aren't generating with the correct markup, so now what I want to do is select any words that begin with http:// and wrap those words in an anchor tag.

I thought I could do something similar to this, but this obviously doesn't work:

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

How can I select the links with jQuery?

CaribouCode
  • 13,998
  • 28
  • 102
  • 174
  • What you are doing is the method I would use, but I'm just wondering what exactly you are wrapping. Is the find bringing back any results? – Darren Crabb Sep 17 '13 at 11:47
  • 1
    possible duplicate of [How to replace plain URLs with links?](http://stackoverflow.com/questions/37684/how-to-replace-plain-urls-with-links) – RobEarl Sep 17 '13 at 11:48
  • @DarrenCrabb the find doesn't return anything because I think it's looking for elements with that name, rather than a string search. – CaribouCode Sep 17 '13 at 11:52
  • Part of the problem, unless it's just a typo, is that `$.fn.html()` is a method, not a member. Make sure you're calling it with parens at the end. And you're right, `$.fn.find` is in fact a method to search for child elements based on a selector, and what you're passing it probably doesn't even run, since that `://` at the end will invalidate it as a query selector. – Ken Bellows Sep 17 '13 at 11:57

1 Answers1

2

You can try to replace it with the RegExp:

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

Provide a function in the second argument of replace() to format each matched URL.

Fiddle example

Artyom Neustroev
  • 8,627
  • 5
  • 33
  • 57