简体   繁体   中英

Extract img tag source from string [Nodejs]

I have a string that looks like this

<table border="0" cellpadding="2" cellspacing="3"><tr><td><img src="https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcRO8iLLBmxFL2lvSfboTwwmH3yGF12PdsJe56rTAzJtbsFfS07I1YM_ZzavbwJREe7bUmhFR3ATyA" border="1"></td><td><ol style="list-style: none; margin: 0; padding: 0;"><strong><li><a href="http://newsday.co.tt/2017/11/14/ansa-mcal-sends-5-containers-of-relief-items/" target="_blank">ANSA McAl sends 5 containers of relief items</a>&nbsp;&nbsp;<font color="#6f6f6f">Trinidad News</font></li></strong><a href="https://news.google.com/story/?hl=en&ned=us" target="_blank">Full coverage</a></ol></td></tr></table>

What I would like to do is extract the source of the image tag. Any suggestions as to where to start to accomplish this?

You could use .split() , which is a very helpful method when trying to extract relevant data from a string:

'<table border="0" cellpadding="2" cellspacing="3"><tr><td><img src="https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcRO8iLLBmxFL2lvSfboTwwmH3yGF12PdsJe56rTAzJtbsFfS07I1YM_ZzavbwJREe7bUmhFR3ATyA" border="1"></td><td><ol style="list-style: none; margin: 0; padding: 0;"><strong><li><a href="http://newsday.co.tt/2017/11/14/ansa-mcal-sends-5-containers-of-relief-items/" target="_blank">ANSA McAl sends 5 containers of relief items</a>&nbsp;&nbsp;<font color="#6f6f6f">Trinidad News</font></li></strong><a href="https://news.google.com/story/?hl=en&ned=us" target="_blank">Full coverage</a></ol></td></tr></table>'
  .split('src="')[1]
  .split('"')[0]

Essentially, this does the following:

  1. Splits the string into an array based on the substring src="
  2. Splits the second item in that array into a new array, based on the substring "
  3. Returns the first element in that array.

There are certainly other ways to do this as well (for instance, regex).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM