views:

40

answers:

1

Ist there any better way to replace/wrap the h*tp://name.tld/request_url?parameter or h*tps://name.tld/request_url?parameter text in some certain html elements with an <a href>

HTML

<div id="posts">
  <div class="post">
    Tweet text 1 http://google.com and other text.
  </div>
  <div class="post">
    Tweet text 2 https://www.google.com and other text.
  </div>
  <div class="post">
    Tweet text 3
  </div>
  <div class="post">
    ...
  </div>
</div>

JavaScript

jQuery('#posts .post').each( function () {
 elem = jQuery(this);
 elem.html(
   elem.text()
    .replace(/(http?:\/\/?\S+)/g, "<a href='$1'>$1</a>")
 ); 
});

Any jQuery.wrap() alternative would be nice too...

A: 

There isn't a much better way, though you can simplify it a bit, like this:

jQuery('#posts .post').each( function () {
  jQuery(this).html(function(i, html) {
    return html.replace(/(http?:\/\/?\S+)/g, "<a href='$1'>$1</a>");
  }); 
});

Use this approach only if you're assured the posts don't contain HTML already, otherwise use what you have.

jQuery works with DOM nodes, not text inside nodes, or rather it does since it's just JavaScript...but it doesn't provide a lot of additional functionality for doing so. jQuery, including .wrap(), focuses around DOM manipulation, not text.

Nick Craver
You're right - wrap() wouldn't work on plain text and text() shouldn't be used if there could be any other HTML code inside the node. My question ist just, whether there is any way to do that with less code/efford? The code could be manipulated earlier also.. e.g. serverside or in the response success function of an AJAX call. Thx for your answer anyway...
gabel
@gabel - There's not really a cheaper way that I've ever seen, unless you do it server-side (which I would) ahead of time.
Nick Craver