开发者

replace() or wrap() http://name.tld/request_url?parameter with <a href="this">...</a>?

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.goog开发者_Go百科le.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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜