简体   繁体   English

从字符串[Nodejs]中提取img标签源

[英]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: 您可以使用.split() ,这是在尝试从字符串中提取相关数据时非常有用的方法:

'<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=" 根据子字符串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). 当然,还有其他方法可以做到这一点(例如,正则表达式)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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