开发者

Grabbing information between key words javascript

I have an app that is being fed HTML into a variable. I need to find the url for the first image file in the HTML (if there is a link at all). This is what I have right now:

var media = row.content.substring(row.content.indexOf('<img src="') + 1, row.c开发者_如何学编程ontent.indexOf('"'));

However, this is not grabbing the correct information. Can anyone see what I'm doing wrong?

Thanks!


Your 2nd indexOf is going to return, at the very least, the " from <img src=", possibly an earlier one. Try:

var ix,
   media = row.content.substring(
      ix = row.content.indexOf('<img src="') + 1, row.content.indexOf('"', ix+10)
   );

which will ensure that it finds the first quote after the one in the img src.

A better way to do this is with a regex:

var media = (row.content.match(/<img[^>]+src\s*=\s*"([^"]+)/) || 0)[1];


row.content.indexOf('"') is returning the position of first double quote which is right after src=

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜