0

I need to convert all RGB into HEX.

First of all I filter all elements to find the ones with style attribute.

wrapper.find('*[style]').filter(function(){
    console.log($(this).attr('style');
});

Than if there is any RGB colors, I need to convert into HEX

function rgbToHex(rgb){
    rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    if (rgb == null) {
        return "";
    } else {
        return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
    }
}
function hex(x) {
    var hexDigits = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f");
    return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
}

function to call is rgbToHex($(this).css('color'));

example of style output: font-family:Arial; background:rgb(255, 0, 0); line-height:10px; color:#fff; border-right-color:rgba(34,64,32,0.5);

How can I filter entire style to grab only the rgb, convert to hex to be able to store the output with new values?

Adrian
  • 491
  • 6
  • 23

1 Answers1

0

My answer:

wrapper.find('*[style]').filter(function(){
    var output = '',
        thisStyle = $(this).attr('style'),
        arrayStyle = thisStyle.split(';').filter(function(el) {
            return el.length != 0
        });
    $.each(arrayStyle, function(i,c){
        var replaceRgb = c.replace(/ /g,'');
        if(c.indexOf('rgb') !== -1) {
            c = c.split(':');
            replaceRgb = c[0]+':'+rgbToHex(c[1].replace(/ /g,''));
        }
        output += replaceRgb+';'
    });
    console.log(output);
});
Adrian
  • 491
  • 6
  • 23