...

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



johnsmith153
11-25-2012, 08: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:


background-image:url('http://domain.com/image.png?v=12345#something-else-here');


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');
background-image:url(URL); // no quotes

rnd me
11-25-2012, 09: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; }
a=a.replace(/^url\(['"]*/gim,"").replace(/['"]*\)$/gim,"")
return a;
}).filter(Boolean);

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

johnsmith153
11-25-2012, 10:53 PM
Hi,

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:


/url\([^)]+\)/gi
...but it also returns all font files, and instead of returning this:

http://www.domain.com/folder/image.png
...it returns this:

url(http://www.domain.com/folder/image.png)


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.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum