Skip to content

Instantly share code, notes, and snippets.

@ppraksa
Created August 19, 2024 10:48
Show Gist options
  • Select an option

  • Save ppraksa/580d16d050f48fd7d1aab4ad84e5a8ea to your computer and use it in GitHub Desktop.

Select an option

Save ppraksa/580d16d050f48fd7d1aab4ad84e5a8ea to your computer and use it in GitHub Desktop.
function getRgb(hex) {
try {
if (
typeof hex !== "string" ||
(hex.length !== 7 && hex.length !== 4) ||
hex[0] !== "#"
) {
throw {
name: "Problem",
message: "This is not a proper string",
};
} else {
hex = hex.split("");
let temp = hex.shift();
temp = hex.join("");
if (hex.length === 3) {
temp = temp.split("").map((item) => item + item);
temp = temp.join("");
}
temp = temp.match(/.{1,2}/g);
let forrmatted = temp.map((item) => parseInt(`0x${item}`));
return `rgb(${forrmatted.join(", ")})`;
}
} catch (e) {
console.error("Problem with converting: " + e.message);
}
}
console.log(getRgb("#FFFFFF"));
console.log(getRgb("#FDA"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment