View Full Version : Slight change to: contents.match(/[^\(]+\.(gif|jpg|jpeg|png)/g)

11-25-2012, 07:57 PM
I have a script which will read the contents of a CSS file and pull out all the URLs (it then preloads those images).

I believe this part of it grabs all the URLs:

var images = contents.match(/[^\(]+\.(gif|jpg|jpeg|png)/g);

...I also believe that grabs the URL ending with the file extension.

(1) I want to be able to grab a version number appended to the file.

(2) I also want to be able to add some form of instruction to the end of a URL to for example tell the script not to pre-load that particular image etc.

So, instead of only ever being able to get the filename and ending with the extension, I want to be able to write that line of code above so it can pull out something like this:


I think I just need that line adjusting slightly? Any ideas? I can do the rest.

Important: a version number and extra stuff after the extension may not always exist. Also, I want it to take into account different ways of writing the CSS, such as this:

background-image:url(URL); // no quotes

rnd me
11-25-2012, 08:27 PM
this should get you started.

in the 'loop', you can examine and reject any url by returning false.
i cleaned up the quotes and parens that polluted some sample CSS i had, but you may need to refine it further for your specific code. also, url() might not have a ";" after it, if it's used as the value of a "background" property instead of a "background-image", so heads up on that.

anyway, here ya go, see what you can do with it:

var strCSS="some css code from ajax or something";
var urls=(strCSS.value.match(/url\([^)]+\)/gi)||[]).map(function(a){
if(a.match("#nocache")){ return false; }
return a;

alert( urls.join("\n") );

11-25-2012, 09:53 PM

Thanks for this, and it's a lot more than I need or expected.

However, I really just need to change this:

var images = contents.match(/[^\(]+\.(gif|jpg|jpeg|png)/g);
...so that it also picks up relevant parts after the extension.

I din't use your entire script as I have all that tried and tested, but I used this part from yours in the line above:

...but it also returns all font files, and instead of returning this:

...it returns this:


So really I just need my line of code changing to include the extra bits at the end.

Thanks for taking the time to post a complete solution though.