The componentToHex function works well for the first component r, but for the other two components, g and b, it doesn't work as expected:
let componentToHex = (val) => {
const a = val.toString(16);
return a.length === 1 ? "0" + a : a;
};
let rgbToHex = (rgb) => {
const hex = rgb.replace("rgb(", "").replace(")", "").split(",");
const r = hex[0];
const g = hex[1];
const b = hex[2];
return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}
console.log(rgbToHex ('rgb(1,255,148)'));
You forgot to convert the components to
number, so you are passing them asstringtocomponentToHex, which expects anumber.As
String.prototype.split()will give you 3strings in this case, you can useArray.prototype.map()withNumber()to easily parse all 3: