Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Substring, Split, String to Number and RGB to HEX

I thought this was an easy task but it is getting really complex. See the Code.

    // Convert "rgb(255, 255, 255)" to (255, 255, 255) and then to Hex code
    var data = {
        color:"rgb(165,199,72)",
        color:"rgb(229,121,74)",
        color:"rgb(105,177,222)"        
    }
    // rgb To Hex Conversion
    var componentToHex = function(c) {            
        var hex = c.toString(16);
        return hex.length == 1 ? "0" + hex : hex;
    }       
    var rgbHex = function(r, g, b) {
        return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
    }


    //Substring "rgb(255, 255, 255)" to "(255, 255, 255)"
    var subStringRGB = function(c){
        var b = c.substring(4, c.length);
    }
    var stringRGBtoNumber = function(c){
        var b = Number(c.split(','));
    }

It is throwing error, cannot read split of undefined. How to fix this?

like image 387
anoop chandran Avatar asked Oct 09 '16 07:10

anoop chandran


3 Answers

subStringRGB does not a return a value. So, if you pass the result of subStringRGB to stringRGBtoNumber c will probably be undefined in stringRGBtoNumber. By the way, stringRGBtoNumber does not return a value, too.

like image 59
mm759 Avatar answered Oct 16 '22 09:10

mm759


You could the functions combine to a singe line with spread operator and some mapping of parts of the values.

subStringRGB and stringRGBtoNumber returns now the processed value.

var data = [{ color:"rgb(165,199,72)"}, { color:"rgb(229,121,74)" },{ color:"rgb(105,177,222)" }],        
    componentToHex = function(c) {            
        var hex = c.toString(16);
        return hex.length == 1 ? "0" + hex : hex;
    },
    rgbHex = function(r, g, b) {
        return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
    },
    subStringRGB = function(c){
        return c.slice(4, -1);
    },
    stringRGBtoNumber = function(c){
        return c.split(',').map(Number); // split and convert all parts to Number
    };
    
console.log(data.map(c => rgbHex(...stringRGBtoNumber(subStringRGB(c.color)).map(componentToHex))));
like image 1
Nina Scholz Avatar answered Oct 16 '22 10:10

Nina Scholz


Processing it with Regular Expression is easy.

var arr = /rgb(\((\d+),(\d+),(\d+)\))/.exec("rgb(255,255,255)");
console.log(arr[1]); // it shows (255,255,255)
var hexVal = (parseInt(arr[2]) << 16) + (parseInt(arr[3]) << 8) + parseInt(arr[4]); // calculate the decimal value
console.log("0x" + hexVal.toString(16)); // it shows 0xffffff
like image 1
hyqhyq_3 Avatar answered Oct 16 '22 09:10

hyqhyq_3