Parsing CSS background-image

后端 未结 2 827
有刺的猬
有刺的猬 2021-01-05 15:06

How do I parse CSS background-image, which supports multiple values, which may be none and functions (e.g. url() and linear-grad

2条回答
  •  攒了一身酷
    2021-01-05 15:45

    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"]
    

提交回复
热议问题