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?
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.
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))));
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With