Javascript function to convert color names to hex codes

Viewed 90183

Is there a built-in function that would convert a color by name into its hex representation? Like I want to pass 'white' and receive '#FFFFFF'. I really want to avoid coding all hundred if's myself :)

16 Answers

@dlauzon suggested I convert my comment into an answer. Thanks for suggesting! Here it is :)

function standardize_color(str){
    var ctx = document.createElement('canvas').getContext('2d');
    ctx.fillStyle = str;
    return ctx.fillStyle;
}

function standardize_color(str){
    var ctx = document.createElement("canvas").getContext("2d");
    ctx.fillStyle = str;
    return ctx.fillStyle;
}

document.getElementById("myspan1").innerHTML = standardize_color("red");
document.getElementById("myspan2").innerHTML = standardize_color("PeachPuff");
document.getElementById("myspan3").innerHTML = standardize_color("PaleGoldenRod"); 
document.getElementById("myspan4").innerHTML = standardize_color("RGB(123,234,142)"); 
document.getElementById("myspan5").innerHTML = standardize_color("HSL(284,6%,49%)");
span { font-weight:800; }
The color named "Red" has a code of: <span id="myspan1">(requires js)</span>.<br>
 ...and color "PeachPuff"'s code is: <span id="myspan2">(requires js)</span>.<br>
 ...and "PaleGoldenRod" is: <span id="myspan3">(requires js)</span>.<br><br>
 
It works with "RGB(123,234,142)" too: <span id="myspan4">(needs js)</span>  
and therefore with: "HSL(284,6%,49%)", which is: <span id="myspan5">(requires js)
</span>.  Handy!

Download & include the w3color.js from w3school.

then in your script you can use any of the following functions:

let c = w3color("violet");
c.darker(n)
c.desaturate(n)
c.isDark(n)
c.lighter(n)
c.saturate(n)
c.toCmyk()
c.toCmykString()
c.toCmykStringDecimal()
c.toHexString()
c.toHsl()
c.toHslString()
c.toHslStringDecimal()
c.toHslaString()
c.toHwb()
c.toHwbString()
c.toHwbStringDecimal()
c.toHwbaString()
c.toName()
c.toNcol()
c.toNcolString()
c.toNcolStringDecimal()
c.toNcolaString()
c.toRgb()
c.toRgbString()
c.toRgbaString()

Run the snippet to see how easily "any" valid CSS color (HSL, names, hex, system colors*, etc.) can be converted to R/G/B values using any element you happen to have laying around.

*Enter a value of background and you'll get your Windows Desktop background color (in Firefox, anyways).

go();
function go() {
  clr.style.backgroundColor = document.getElementById('txt').value;
  document.getElementById('rgb').innerHTML = window.getComputedStyle(clr).backgroundColor;
}
* { margin:0; box-sizing:border-box; font-family:verdana; overflow:hidden; }
#txt,#rgb,#clr { height:30vh; width:97vw; padding:5vmin; margin:2vmin; font-size:13vh; border:1vmin solid; text-align:center; vertical-align:middle;}
#txt{margin-bottom:0;}
<input type='text' id='txt' onkeyup='go()' value='chartreuse' placeholder='Enter any css color . . .' autofocus>
<div id='clr'></div>
<div id='rgb'></div>

The solution from Ties converted to TypeScript:

export const getHexColorFromLiteral = (
  colorStr:
    | 'aliceblue'
    | 'antiquewhite'
    | 'aqua'
    | 'aquamarine'
    | 'azure'
    | 'beige'
    | 'bisque'
    | 'black'
    | 'blanchedalmond'
    | 'blue'
    | 'blueviolet'
    | 'brown'
    | 'burlywood'
    | 'cadetblue'
    | 'chartreuse'
    | 'chocolate'
    | 'coral'
    | 'cornflowerblue'
    | 'cornsilk'
    | 'crimson'
    | 'cyan'
    | 'darkblue'
    | 'darkcyan'
    | 'darkgoldenrod'
    | 'darkgray'
    | 'darkgreen'
    | 'darkkhaki'
    | 'darkmagenta'
    | 'darkolivegreen'
    | 'darkorange'
    | 'darkorchid'
    | 'darkred'
    | 'darksalmon'
    | 'darkseagreen'
    | 'darkslateblue'
    | 'darkslategray'
    | 'darkturquoise'
    | 'darkviolet'
    | 'deeppink'
    | 'deepskyblue'
    | 'dimgray'
    | 'dodgerblue'
    | 'firebrick'
    | 'floralwhite'
    | 'forestgreen'
    | 'fuchsia'
    | 'gainsboro'
    | 'ghostwhite'
    | 'gold'
    | 'goldenrod'
    | 'gray'
    | 'green'
    | 'greenyellow'
    | 'honeydew'
    | 'hotpink'
    | 'indianred'
    | 'indigo'
    | 'ivory'
    | 'khaki'
    | 'lavender'
    | 'lavenderblush'
    | 'lawngreen'
    | 'lemonchiffon'
    | 'lightblue'
    | 'lightcoral'
    | 'lightcyan'
    | 'lightgoldenrodyellow'
    | 'lightgray'
    | 'lightgreen'
    | 'lightpink'
    | 'lightsalmon'
    | 'lightseagreen'
    | 'lightskyblue'
    | 'lightslategray'
    | 'lightsteelblue'
    | 'lightyellow'
    | 'lime'
    | 'limegreen'
    | 'linen'
    | 'magenta'
    | 'maroon'
    | 'mediumaquamarine'
    | 'mediumblue'
    | 'mediumorchid'
    | 'mediumpurple'
    | 'mediumseagreen'
    | 'mediumslateblue'
    | 'mediumspringgreen'
    | 'mediumturquoise'
    | 'mediumvioletred'
    | 'midnightblue'
    | 'mintcream'
    | 'mistyrose'
    | 'moccasin'
    | 'navajowhite'
    | 'navy'
    | 'oldlace'
    | 'olive'
    | 'olivedrab'
    | 'orange'
    | 'orangered'
    | 'orchid'
    | 'palegoldenrod'
    | 'palegreen'
    | 'paleturquoise'
    | 'palevioletred'
    | 'papayawhip'
    | 'peachpuff'
    | 'peru'
    | 'pink'
    | 'plum'
    | 'powderblue'
    | 'purple'
    | 'rebeccapurple'
    | 'red'
    | 'rosybrown'
    | 'royalblue'
    | 'saddlebrown'
    | 'salmon'
    | 'sandybrown'
    | 'seagreen'
    | 'seashell'
    | 'sienna'
    | 'silver'
    | 'skyblue'
    | 'slateblue'
    | 'slategray'
    | 'snow'
    | 'springgreen'
    | 'steelblue'
    | 'tan'
    | 'teal'
    | 'thistle'
    | 'tomato'
    | 'turquoise'
    | 'violet'
    | 'wheat'
    | 'white'
    | 'whitesmoke'
    | 'yellow'
    | 'yellowgreen'
) => {
    const div = document.createElement('div')
    div.style.color = colorStr
    document.body.appendChild(div)

    const computedColor = window.getComputedStyle(div).color
    const matchResult = computedColor.match(/\d+/g)
    if (matchResult !== null) {
        const colors = matchResult.map((a) => parseInt(a, 10))

        document.body.removeChild(div)
        return colors.length >= 3
            ? '#' + ((1 << 24) + (colors[0] << 16) + (colors[1] << 8) + colors[2]).toString(16).substr(1)
            : false
    }

    return false
}

This function request a named color and send return a hexadecimal color value. If the named color not supported (example "whyte") send back black color by default but on consol you can find a warning: Not supported named color: ${namedColor}

const namedColorToHex = namedColor => {
    const html = document.querySelector("html");
    const originalColor = html.style.color;
    html.style.color = namedColor;
    const rgbFormatBgColor = window.getComputedStyle(html).color;
    if (namedColor !== "black" && rgbFormatBgColor === "rgb(0, 0, 0)") {
        console.warn(`Not supported named color: ${namedColor}`);
    }
    html.style.color = originalColor;
    const regEx = /(\d+)/g;
    const result = rgbFormatBgColor.match(regEx);
    let hexColor = `#`;
    result.forEach(value => {
        let hex = Number(value).toString(16);
        if (hex.length === 1) {
            hex = `0${hex}`;
        }
        hexColor += hex;
    });
    return hexColor;
};

With Firefox 94 you get the rgb color when formated with a color name. But you have to inject the dummy element at first to the page.

// Vanilla and jQuery

console.clear();

var 
  colors = ['cyan', 'magenta', 'yellow']
  dummy     = {},
  colorObj  = {},
  rgbString = '',
  rgb2hex   = function(rgb) {
    rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
    return (rgb && rgb.length === 4) ? "#" +
    ("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
    ("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
    ("0" + parseInt(rgb[3],10).toString(16)).slice(-2) : '';
  }
;

$(colors).each(function(i, color) {
  dummy = $('<b style="background-color:' + color + '"></b>');
  // inject the dummy
  $('body').append(dummy);
  // get the rgb color 
  rgbString = dummy.css('background-color');
  // build an object with 'color name', 'rgb color' and 'hex color'
  colorObj[i] = [color, rgbString, rgb2hex(rgbString)]; 
  // delete the dummy 
  dummy.remove();  
});

console.dir(colorObj);

If you need an array with all 140 color names

colors = [
  'aliceblue',
  'antiquewhite',
  'aqua',
  'aquamarine',
  'azure',
  'beige',
  'bisque',
  'black',
  'blanchedalmond',
  'blue',
  'blueviolet',
  'brown',
  'burlywood',
  'cadetblue',
  'chartreuse',
  'chocolate',
  'coral',
  'cornflowerblue',
  'cornsilk',
  'crimson',
  'cyan',
  'darkblue',
  'darkcyan',
  'darkgoldenrod',
  'darkgray',
  'darkgreen',
  'darkkhaki',
  'darkmagenta',
  'darkolivegreen',
  'darkorange',
  'darkorchid',
  'darkred',
  'darksalmon',
  'darkseagreen',
  'darkslateblue',
  'darkslategray',
  'darkturquoise',
  'darkviolet',
  'deeppink',
  'deepskyblue',
  'dimgray',
  'dodgerblue',
  'firebrick',
  'floralwhite',
  'forestgreen',
  'fuchsia',
  'gainsboro',
  'ghostwhite',
  'gold',
  'goldenrod',
  'gray',
  'green',
  'greenyellow',
  'honeydew',
  'hotpink',
  'indianred',
  'indigo',
  'ivory',
  'khaki',
  'lavender',
  'lavenderblush',
  'lawngreen',
  'lemonchiffon',
  'lightblue',
  'lightcoral',
  'lightcyan',
  'lightgoldenrodyellow',
  'lightgray',
  'lightgreen',
  'lightpink',
  'lightsalmon',
  'lightseagreen',
  'lightskyblue',
  'lightslategray',
  'lightsteelblue',
  'lightyellow',
  'lime',
  'limegreen',
  'linen',
  'magenta',
  'maroon',
  'mediumaquamarine',
  'mediumblue',
  'mediumorchid',
  'mediumpurple',
  'mediumseagreen',
  'mediumslateblue',
  'mediumspringgreen',
  'mediumturquoise',
  'mediumvioletred',
  'midnightblue',
  'mintcream',
  'mistyrose',
  'moccasin',
  'navajowhite',
  'navy',
  'oldlace',
  'olive',
  'olivedrab',
  'orange',
  'orangered',
  'orchid',
  'palegoldenrod',
  'palegreen',
  'paleturquoise',
  'palevioletred',
  'papayawhip',
  'peachpuff',
  'peru',
  'pink',
  'plum',
  'powderblue',
  'purple',
  'red',
  'rosybrown',
  'royalblue',
  'saddlebrown',
  'salmon',
  'sandybrown',
  'seagreen',
  'seashell',
  'sienna',
  'silver',
  'skyblue',
  'slateblue',
  'slategray',
  'snow',
  'springgreen',
  'steelblue',
  'tan',
  'teal',
  'thistle',
  'tomato',
  'turquoise',
  'violet',
  'wheat',
  'white',
  'whitesmoke',
  'yellow',
  'yellowgreen'
]
Related