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
  • 19,268
  • 13
  • 43
  • 51

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
  • 534
  • 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
  • 47,502
  • 56
  • 171
  • 285
0

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

Oleks
  • 31,955
  • 11
  • 77
  • 132
user489998
  • 4,473
  • 2
  • 29
  • 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,955
  • 11
  • 77
  • 132
kennebec
  • 102,654
  • 32
  • 106
  • 127
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,955
  • 11
  • 77
  • 132