Substring, Split, String to Number, and RGB for HEX

I thought this was not an easy task, but it is becoming very difficult. See 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(',')); } 

Throws an error, cannot read the undefined split. How to fix it?

+6
source share
3 answers

You can combine functions with one line with the distribution operator and some display of parts of the values.

subStringRGB and stringRGBtoNumber now returns 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)))); 
+1
source

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

+2
source

Processing it with regex 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 
+1
source

All Articles