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

How to Convert Color Names to Hex Codes in JavaScript?

Mary-Kate Olsen
Release: 2024-10-31 02:38:31
Original
633 people have browsed it

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;
}
Copy after login

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'
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template