Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What regex to match all occurrences of css urls?

i have a css file with a bunch of background image urls:

.alert-01 {
  background: url('img/alert-01.jpg') center no-repeat;
}
.alert-02 {
  background: url('img/alert-02.jpg') center no-repeat;
}
.alert-03 {
  background: url('img/alert-03.jpg') center no-repeat;
}
.alert-04 {
  background: url('img/alert-04.jpg') center no-repeat;
}

And I'd like to write a regex that would strip out the urls.

So initially i would get:

url('img/alert-01.jpg')
url('img/alert-02.jpg')
url('img/alert-03.jpg')
url('img/alert-04.jpg')

Which i could then replace bits to turn them into html <img> blocks.

I'm fine with the last bit, but my regex skills are a bit rusty.

My latest try was this: /^url\(.*?g\)$/ig

Any help?

BTW I was doing this all in javascript, but the language shouldn't affect the regex really.

Thanks in advance!

Also, just to note, i can't guarantee that the files will always be jpg and may be jpeg, png etc. Also that the arguments into background will always be the same. Hence why i want to extract just the url part.

like image 809
Ryk Waters Avatar asked Oct 22 '13 12:10

Ryk Waters


2 Answers

I came to this question from google. Old one, but none of the answer is discussing about data:image/* urls. Here is what I found on another google result that will only match http or relative urls.

/url\((?!['"]?(?:data):)['"]?([^'"\)]*)['"]?\)/g

I hope this would help other people coming from search engines.

like image 124
Rizwan Avatar answered Oct 23 '22 21:10

Rizwan


/^url\((['"]?)(.*)\1\)$/

with jQuery :

var bg = $('.my_element').css('background-image'); // or pure js like element.style.backgroundImage
    bg = /^url\((['"]?)(.*)\1\)$/.exec(bg);
    bg = bg ? bg[2] : false;
if(bg) {
// Do something
}

Cross with Chrome / Firefox

http://jsfiddle.net/KFWWv/

like image 35
l2aelba Avatar answered Oct 23 '22 23:10

l2aelba