Color Converter

Convert between RGB, HEX, HSL color formats

javascript (ES2020) 2025-11-12 color conversion rgb hex hsl

Description

A utility for converting colors between different formats: RGB, HEX, and HSL. Handles color space conversions and validation.

Features

  • RGB to HEX conversion
  • HEX to RGB conversion
  • HSL conversion
  • Color validation

Code

RAW
class ColorConverter {  static rgbToHex(r, g, b) {    return '#' + [r, g, b].map(x => {      const hex = x.toString(16);      return hex.length === 1 ? '0' + hex : hex;    }).join('');  }    static hexToRgb(hex) {    const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);    return result ? {      r: parseInt(result[1], 16),      g: parseInt(result[2], 16),      b: parseInt(result[3], 16)    } : null;  }    static rgbToHsl(r, g, b) {    r /= 255;    g /= 255;    b /= 255;        const max = Math.max(r, g, b);    const min = Math.min(r, g, b);    let h, s, l = (max + min) / 2;        if (max === min) {      h = s = 0;    } else {      const d = max - min;      s = l > 0.5 ? d / (2 - max - min) : d / (max + min);            switch (max) {        case r: h = ((g - b) / d + (g < b ? 6 : 0)) / 6; break;        case g: h = ((b - r) / d + 2) / 6; break;        case b: h = ((r - g) / d + 4) / 6; break;      }    }        return {      h: Math.round(h * 360),      s: Math.round(s * 100),      l: Math.round(l * 100)    };  }    static isValidHex(hex) {    return /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(hex);  }}module.exports = ColorConverter;
RAW
const ColorConverter = require('./colorConverter');// RGB to HEXconst hex = ColorConverter.rgbToHex(255, 128, 0);console.log('HEX:', hex);// HEX to RGBconst rgb = ColorConverter.hexToRgb('#FF8000');console.log('RGB:', rgb);// RGB to HSLconst hsl = ColorConverter.rgbToHsl(255, 128, 0);console.log('HSL:', hsl);// Validate HEXconsole.log('Valid HEX:', ColorConverter.isValidHex('#FF8000'));

Comments

No comments yet. Be the first to comment!