0

Yes, I know, I know.

Should work everywhere :)

But especially those I find tricky:

<div style="background-image:url('img.png');"></div>
<div style='background-image:url("img.png");'></div>
<div style='background-image:url(img.png);'></div>
<div style='background-image:url(../../img.png);'></div>
<div style='background:  #ffffff   url( "img.png" )   no-repeat right top;'></div>

Note: should work in JavaScript.

Community
  • 1
  • 1
Aron Woost
  • 17,389
  • 13
  • 42
  • 49

5 Answers5

1

If you want anything inside every url(...)

url\(\s*(['"]?)(.*?)\1\s*\)

url    # literal characters 
\(     # escaped left parenthesis to treat it as literal
\s*    # 0 or more white-space characters
(      # 1st capture group
 ['"]? # either ' or " or neither
)      # end 1st capture group
(.*?)  # 2nd (main) capture group, any characters, reluctantly
\1     # back-reference group #1, to ensure that same quote type is used at end
\s*    # 0 or more white-space characters
\)     # escaped right parenthesis to treat it as literal

http://rubular.com/r/P6FJwxC0L7

If you want only .png files inside every url(....png)

url\(\s*(['"]?)(.*?\.png)\1\s*\)

EDIT: allowance for spaces, and removed useless back-reference

GetSet
  • 524
  • 2
  • 6
0

I think you should get the inner text of the style attribute somehow, and then use the following regex:

background-image:(?: )*url\((?:'|")?([^'"]*)(?:'|")?\);

The only matched group will be the contents of background-image's url, without optional leading and/or trailing quotes (either " or ')

bevacqua
  • 45,496
  • 53
  • 165
  • 281
0

This should work \\(['"]?([\w./]+)

Oleks
  • 31,334
  • 11
  • 76
  • 131
user489998
  • 4,293
  • 2
  • 28
  • 35
0

Another way to go would be to anchor the start of the match after url( and possible spaces or quote, \burl\( *['"]? and match everything that follows until you find a space, quote, or closed parenthesis ([^'" )]+).

var txt='url("/webworks/art/yankee/yankee2.gif")';
var url=(/\burl\( *['"]?([^'" )]+)/.exec(txt)||[])[1];

url>>
/webworks/art/yankee/yankee2.gif

written with `|| []`` at the end allows a non-match to return undefined rather than throwing an error.

Oleks
  • 31,334
  • 11
  • 76
  • 131
kennebec
  • 98,993
  • 30
  • 103
  • 125
0

I'd match urls by a simple pattern first /url\([^(]+\)/ig, and then remove all the unnecessary symbols from the result:

var matches = html.match(/url\([^(]+\)/ig);
for(var i = 0; i < matches.length; i++)
    // this is a clean url
    var url = matches[i].replace(/(^url\s*\(\s*['"]?)|(['"]?\s*\)$)/ig, '');

You could find the full code snippet on jsfiddle.

Oleks
  • 31,334
  • 11
  • 76
  • 131