0

So I created this function to extract an RGB array from a style attribute, but everything inside me is screaming and telling me there is a better way of doing it.

My style attribute looks like this:

style="fill: rgb(0, 0, 0);"

so I wrote a function that looks like this:

var _extractRGBfromStyle = function (styles) {

    // Create some variables
    var length = styles.length - 1,
        index = styles.indexOf(';');

    // If we only have one style applied to the element
    if (length === index) {

        // Get the first part
        var rgb = styles.split('(');

        // If we have more than one result
        if (rgb.length > 1) {

            // Get our last part
            rgb = rgb[1].split(')');

            // If we have more than one result
            if (rgb.length > 1) {

                // Do one last split and return it
                return rgb[0].split(',');
            }
        }
    }

    // Fallback
    return [0, 0, 0];
};

I really don't like the nested splits. Is there a better way of doing this?

r3plica
  • 13,017
  • 23
  • 128
  • 290
  • 1
    Possible duplicate of [How to extract r, g, b, a values from CSS color?](http://stackoverflow.com/questions/3751877/how-to-extract-r-g-b-a-values-from-css-color) – Tom Jan 21 '16 at 19:11
  • This may be helpful: https://stackoverflow.com/questions/3048838/jquery-css-color-value-returns-rgb – Ajwhiteway Jan 21 '16 at 19:14
  • It depends but if you know you're just getting RGB why not just use one split, loop the array ParseInt the values and everything that is not NaN will be your numbers? It's dirty but would be simpler to read. – Daniel Tate Jan 21 '16 at 19:15
  • it will and did :) I have posted my solution – r3plica Jan 21 '16 at 19:22

2 Answers2

0

I answered this by using regex:

// Extract our hex from our style
var _rgb2hex = function (style) {

    // match our fill style
    var rgb = style.match(/^fill:\s?rgb[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)\);/i);

    // If our array exists and is a length of 4
    if (rgb && rgb.length === 4) {

        // Create our hex
        var hex = ("0" + parseInt(rgb[1], 10).toString(16)).slice(-2) + ("0" + parseInt(rgb[2], 10).toString(16)).slice(-2) + ("0" + parseInt(rgb[3], 10).toString(16)).slice(-2);

        // Return our hex
        return hex;
    }

    // Fallback
    return '';
};
r3plica
  • 13,017
  • 23
  • 128
  • 290
0

As far as I know it's only possible using string splitting, but you van do an inline Regex split like so

yourstyleattribute.replace(/^rgba?(|\s+|)$/g,'').split(',');

which will split all the numeric RBG values into an array.

Hope this helps.

TechnicalTophat
  • 1,655
  • 1
  • 15
  • 37