Home > Back-end >  find text on the page and put it in a tag
find text on the page and put it in a tag

Time:12-25

I have <div> with text. This text contain URLs.

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

Question is: how to take URL and place it in <img src="here">?

CodePudding user response:

You can use match to get the URL from the text, then add it as the src attribute of any image.

$('#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>

CodePudding user response:

Try this https://regex101.com/r/pM2GrT/1 Regex code Code generator

  • Related