0

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
1
  • 1
    Can you guaraantee they'll all be in the exact same form? I'm sure you're well awware that regex isn't suitably equipped for HTML parsing. At any rate, in this form you could just match anything between quotes. Commented Sep 18, 2013 at 12:16

2 Answers 2

5

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;
Sign up to request clarification or add additional context in comments.

Comments

2

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'));
});

3 Comments

Do you see a jQuery tag anywhere?
@Kolink Did you use regex ?
@GibboK Neither. See my answer for the best solution to this problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.