hexToRgb
A utility function to convert a hexadecimal color string to RGB or RGBA format.> hexToRgb(hex: string): string
- hex (string): A string representing the color in hexadecimal format. The input can be in short form (e.g., "#abc" or "#abcd") or long form (e.g., "#aabbcc" or "#aabbccdd").
- Returns: A string representing the color in either "rgb" or "rgba" format:
- For hex colors without an alpha channel: `rgb(r, g, b)`
- For hex colors with an alpha channel: `rgba(r, g, b, a)`
Example
import { hexToRgb } from "@explita/daily-toolset";
// Convert a hex color without an alpha channel
const rgbColor = hexToRgb("#ff6347");
console.log(rgbColor); // Output: "rgb(255, 99, 71)"
// Convert a short hex color without an alpha channel
const shortRgbColor = hexToRgb("#abc");
console.log(shortRgbColor); // Output: "rgb(170, 187, 204)"
// Convert a hex color with an alpha channel
const rgbaColor = hexToRgb("#ff6347cc");
console.log(rgbaColor); // Output: "rgba(255, 99, 71, 0.80)"
Use Cases
- Converting hex color codes (with or without alpha) to RGB or RGBA format for use in CSS or JavaScript color manipulation.
- Ensuring consistency when dealing with color formats in web development or design systems.
- Handling shorthand hex color formats and expanding them to full RGB or RGBA values.