How do I parse CSS background-image
, which supports multiple values, which may be none
and functions (e.g. url()
and linear-grad
Looking at the current W3C Candidate Recommendation for CSS3 (in particular, see background-image and uri), it is structured as follows:
<background-image> = <bg-image> [ , <bg-image> ]*
<bg-image> = <image> | none
<image> = <url> | <image-list> | <element-reference> | <image-combination> | <gradient>
... (you can find the rest of syntax for images here)
EDIT:
You will need to parse for matching parenthese or none
then, and the former is not possible with regex. This post has a pseudo code for the algorithm: Python parsing bracketed blocks.
function split (string) {
var token = /((?:[^"']|".*?"|'.*?')*?)([(,)]|$)/g;
return (function recurse () {
for (var array = [];;) {
var result = token.exec(string);
if (result[2] == '(') {
array.push(result[1].trim() + '(' + recurse().join(',') + ')');
result = token.exec(string);
} else array.push(result[1].trim());
if (result[2] != ',') return array
}
})()
}
split("linear-gradient(top left, red, rgba(255,0,0,0)), url(a), image(url" +
"(b.svg), 'b.png' 150dpi, 'b.gif', rgba(0,0,255,0.5)), none").toSource()
["linear-gradient(top left,red,rgba(255,0,0,0))", "url(a)",
"image(url(b.svg),'b.png' 150dpi,'b.gif',rgba(0,0,255,0.5))", "none"]