0

I am looking for an updated answer to this question Parsing CSS background-image

The answer there seems to get things right but unfortunately it strips out the percentage values on stop points in gradients (see my comment there for an example)

So what I am hoping someone could help me with is an updated regex like joos accepted answer that doesn't strip percentage stop point values from gradients...

Or maybe there is another way?

Community
  • 1
  • 1
David O'Sullivan
  • 2,969
  • 4
  • 21
  • 24
  • I don't think CSS `background-image` property values meet the criteria for a Regular Language and so cannot be successfully (reliably and robustly) parsed with a Regular Expression. – Dai Feb 20 '15 at 02:17
  • actually looking at it, all I need I think is to split the property on any comma that is not inside brackets, all I need is an array of the background images... – David O'Sullivan Feb 20 '15 at 02:22

1 Answers1

0

Ok I have done this which seems to work ok- probably dont need to use jQuery but I'll post an update...

splitBgImage : function(string) {
        //split the background-image string into an array of characters
        //iterate over the array of characters adding each to the bgimg variable
        //if we encounter a ( then we increment brackets by one
        //if we encounter a ) then we decrement brackets by one
        //if we encounter a , then if brackets == 0 then we push the bgimg property to the bgimgs array and set the bgimg property back to ''
        //if we are at the end of the array add whats left to bgimgs minus the ';'
        var brackets = 0, bgimg = '', bgimgs = [], splitString = string.split(''), totalLength = jQuery(splitString).length;
        jQuery.each(splitString, function(index, char){
            if(char == '(')
                {
                brackets ++;
                }
            if(char == ')')
                {
                brackets -- ;
                }
            if(char == ',' && brackets == 0)
                {
                bgimgs.push(bgimg);
                bgimg = ''; 
                }
            else
                {
                if(char != ';')
                bgimg += char;  
                }
            if(index == totalLength-1)
                {
                bgimgs.push(bgimg); 
                }
        });
        return bgimgs;
    }
David O'Sullivan
  • 2,969
  • 4
  • 21
  • 24