简体   繁体   中英

Regular expression for finding image urls in <img> tag in HTML using javascript

What is the faster way to collect in an array srcs urls from image tag?

var result = [];
var html= '<img src="http://mysite.com/a/b/c/images/aaa.jpg"><img src="http://mysite.com/a/b/c/images/bbb.jpg"><img src="http://mysite.com/a/b/c/images/ccc.jpg">'

so the result should be in listed in the array as:

http://mysite.com/a/b/c/images/aaa.jpg
http://mysite.com/a/b/c/images/bbb.jpg
http://mysite.com/a/b/c/images/ccc.jpg

Don't try to parse the string yourself:

var tmp = document.createElement('div');
tmp.innerHTML = html;
var imgs = tmp.getElementsByTagName('img'), l = imgs.length, i;
for( i=0; i<l; i++) result[i] = imgs[i].src;

Using jQuery:

var result = [];
var html   = '<img src="http://mysite.com/a/b/c/images/aaa.jpg"><img src="http://mysite.com/a/b/c/images/bbb.jpg"><img src="http://mysite.com/a/b/c/images/ccc.jpg">';

$(html).each(function(){
  result.push($(this).attr('src'));
});

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