replace() or wrap() http://name.tld/request_url?pa

2019-07-19 01:58发布

问题:

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

Here is my code:

jQuery('#posts .post').each(function() {
  elem = jQuery(this);
  elem.html(
    elem.text()
    .replace(/(http?:\/\/?\S+)/g, "<a href='$1'>$1</a>")
  );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<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>

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

回答1:

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.