用…替换()或wrap()http://name.tld/request_url?参数?

问题描述 投票:2回答:1

我有更好的方法来替换/包装h*tp://name.tld/request_url?parameterh*tps://name.tld/request_url?parameter文本在某些某些html元素与<a href>

这是我的代码:

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>

任何jQuery.wrap()替代品都会很好。

javascript jquery regex replace
1个回答
4
投票

没有更好的方法,虽然你可以简化它,如下所示:

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

只有当您确信帖子中不包含HTML时才使用此方法,否则请使用您拥有的内容。

jQuery适用于DOM节点,而不是节点内的文本,或者更确切地说它是因为它只是JavaScript ...但它没有提供很多额外的功能。 jQuery,包括.wrap(),专注于DOM操作,而不是文本。

© www.soinside.com 2019 - 2024. All rights reserved.