【问题标题】:find text on the page and put it in a tag在页面上查找文本并将其放入标签中
【发布时间】:2021-12-24 19:26:22
【问题描述】:

我有带有文字的<div>。此文本包含 URL。

<div id="text">
 text,text, https://static01.nyt.com/images/2021/09/14/science/07CAT-STRIPES/07CAT-STRIPES-mediumSquareAt3X-v2.jpg 
</div>
<script>
    $('#text').each(function() {
        var exp = /(\b[^"'](https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    })
    
</script>

问题是:如何获取URL并将其放入&lt;img src="here"&gt;

【问题讨论】:

  • &lt;div id="text&gt; 中缺少"

标签: jquery


【解决方案1】:

您可以使用match 从文本中获取 URL,然后将其添加为任何图像的src 属性。

$('#text').each(function() {
  var exp = /((https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig
        
  // Find the URL in the div
  const urls = $(this).text().match(exp)
  
  // Loop through the URLs
  for (let i = 0; i < urls.length; i++) {
  
    // As an example, we're setting the img src that corrosponds to the
    // current index
    $('img').eq(i).attr('src', urls[i])
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="text">
 text,text, https://static01.nyt.com/images/2021/09/14/science/07CAT-STRIPES/07CAT-STRIPES-mediumSquareAt3X-v2.jpg, text, https://static01.nyt.com/images/2021/09/14/science/07CAT-STRIPES/07CAT-STRIPES-mediumSquareAt3X-v2.jpg 
</div>

<img>

<img>

【讨论】:

  • 如果网址超过一个,它只显示第一张图片
  • 好吧,您没有指定可以有多个 URL。我只能用你给我的东西工作。
  • 更新了使用多个 URL 的答案
【解决方案2】:

试试这个 https://regex101.com/r/pM2GrT/1 正则表达式代码代码生成器

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-13
    相关资源
    最近更新 更多