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 want the number part (the
val) to be a number before you calltoStringon it. If it's a string when you calltoStringon it, it'll remain as-is:Also note that you should always declare variables before using them (else errors will be thrown in strict mode, or they'll be implicitly global, which can cause bugs).
As you can see above, the function that takes and transforms the input numbers can be made more elegant by matching digit characters, mapping to
componentToHex, and then joining.