Oliver Nassar

RegExp for grabbing the background-image of an HTMLElement

April 18, 2011

I've got an HTMLElement which has a background image. I need to grab the path to the url. The problem is there are a few syntaxes that people can type in CSS to specify the path to an image, and different browsers render the value of the background-image style-property of a node different.

For example, I could set the background-image property of a node as follows:

.node {
    background-image: url(/path/to/image.png);
}
.node {
    background-image: url('/path/to/image.png');
}
.node {
    background-image: url("/path/to/image.png");
}

When accessing the background-image style-property of a node, different browsers will choose how to return the value (eg. sometimes with wrapping apostrophes, quotes or without).

The following regular expression solved my problem:

/url((["|']?)([^"']+)1)/

This can be tested in a console with the following:

clear();
var a = 'url("/path/to/image.png")',
    b = 'url('/path/to/image.png')',
    c = 'url(/path/to/image.png)';

var path = c.replace(/url((["|']?)([^"']+)1)/, '$2');
console.log(path);

Update

Tried looking into "zero-width negative look-ahead assertion" in order to make the expression more finite. Specifically, it's somewhat loose as it stands right now it potentially allows the following:

url('/path/to/im'age.png')

Ideally, the catch-all currently defined by "([^"']+) ought to be restricted to exclude only the character (if any) with-which the url was prepended (eg. the quote or single-quote/apostrophe).

This is really tough to write though, and after an hour or so, I've basically given up. It's not worth the time and as it stands, it good enough to catch 99% of cases. Will update if I find that missing piece.