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(\'
Use the following regex:
/\burl\([^)]+\)/gi
There's no need to use anchors (^
and $
) as they would restrict the match over whole string input and hence fail. To capture the image path separately so that you can use it easily (and avoid substring) when constructing your <img>
tags use:
/\burl\('([^']+)'\)/gi
This captures img/alert-xx.jpg
in group one.
/^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/
Using a tool like Regexper we can see what your regular expression is matching:
As you can see there are a few problems with this:
What we instead need to do is match just "url(" [any character] ")"
. And we can do that using:
/url\(.*?\)/ig
Note that I've removed the requirement for the URL ending in "g" in case the image type is .gif
or any other non-jpg, jpeg or png.
Edit: As Seçkin M commented below: what if we don't want any other url's; such as fonts which have .ttf or .eot? What is the easiest way to define an allowed extensions group?
For this we can predefine what extensions we're looking for by putting our extensions within brackets, separated with |
. For instance, if we wanted to match only gif
, png
, jpg
or jpeg
, we could use:
/url\(.*?(gif|png|jpg|jpeg)\'\)/ig
You were just not accounting for the closing quote
url\(.*g\'\)
and anchoring
Try:
/url\(.*?g'\)/ig
Your mistake was including ^
and $
in the regexp, which anchors it to the beginning and end of the input string. And you forgot to allow for the quote.
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.