Hugo Chan
Hugo Chan

Reputation: 153

Retrive all image urls from a css

I have been searching the web for a couple of days and I have not been able to find what I need.

What I want is to match all background image urls within a CSS file using javascript regular expressions.

ex:

background:url('images/sprite-global.png'); // should return 'images/sprite-global.png'
background-image: url('images/sprite-global.png'); should also return 'images/sprite-global.png'
background:url( 'images/sprite-global.png' );// should return 'images/sprite-global.png' even if we have spaces.
background:url('http://mysite.com/css/images/sprite-global.png'); // should return 'http://mysite.com/css/images/sprite-global.png'

However, it should not return anything for:

{
display:none;
}

It looks easy but so far , the best result I have is: url('images/sprite-global.png') using:

/url\(([^\)]+\)/i

Does anyone know which expression I could use?

Thanks

Hugo

Upvotes: 3

Views: 763

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191799

http://jsfiddle.net/2V5Gg/2/

/url\((.*?)\)/

I'm not exactly sure what your requirements are since url can also use double quotes or no quotes or if you would be worried about the paths containing the string "url" or parentheses, but this at least works with your examples. Rather than try to get an exact regex to handle trimming, it's easier to just use $.trim.

Upvotes: 1

Related Questions