Home  >  Article  >  Web Front-end  >  How to Convert Color Names to Hex Codes in JavaScript?

How to Convert Color Names to Hex Codes in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-31 02:38:31609browse

How to Convert Color Names to Hex Codes in JavaScript?

Converting Color Names to Hex Codes in Javascript

In Javascript, there isn't an inbuilt function specifically designed to convert color names to their hexadecimal representations. However, we can create one using a comprehensive list of color names and their corresponding hex codes.

Below is a Javascript function that takes a color name and returns its hex code equivalent:

function colourNameToHex(colour) {
  var colours = {
    "aliceblue": "#f0f8ff",
    "antiquewhite": "#faebd7",
    "aqua": "#00ffff",
    "aquamarine": "#7fffd4",
    "azure": "#f0ffff",
    ... // Omitted for brevity
    "yellowgreen": "#9acd32",
  };

  if (typeof colours[colour.toLowerCase()] != 'undefined')
    return colours[colour.toLowerCase()];

  return false;
}

This function takes a color name (in lower case) as an argument and looks it up in the colours object. If the color exists in the list, the function returns its hex code; otherwise, it returns false.

For example:

const hexCode = colourNameToHex('white');
console.log(hexCode); // '#ffffff'

The above is the detailed content of How to Convert Color Names to Hex Codes in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn