My goal is to collect all images urls with jquery that are inserted in the html code like this:
style="background: url(...)"
or
style="background-image: url(...)"
In the first example there may be different cases (like adding repeat, position, and changing the order of the tags).
I suppose regexp will be the best way to do it, but I'm not very good at it.
Thanks!
Yep. I would go with regexp.
Here is an example:
var img_urls=[];
$('[style*="background"]').each(function() {
var style = $(this).attr('style');
var pattern = /background.*?url\('(.*?)'\)/g
var match = pattern.exec(style);
if (match) {
img_urls.push(match[1]);
//just for testing, not needed:
$('#result').append('<li>'+match[1]+'</li>');
}
});
If it is possible to have urls in style that are not part of the background, while background could be without image, the regexp should be more complicated and, for the code maintainability sake, I would simply add another "if" rather than make regexp with negative lookahead (which many people have difficulty to read).
So, the code would be then like this:
var img_urls=[];
$('[style*="background"]').each(function() {
var style = $(this).attr('style');
var pattern = /background(.*?)url\('(.*?)'\)/ig
var match = pattern.exec(style);
if (match && match.length > 0) {
if (match[1].indexOf(';')>0) return;
img_urls.push(match[2]);
//just for testing, not needed:
$('#result').append('<li>'+match[2]+'</li>');
}
});
You can play with it on this fiddle: http://jsfiddle.net/Exceeder/nKPbn/