Home > Web Front-end > JS Tutorial > body text

Is there a built-in JavaScript Function to Convert Color Names to Hex Codes?

Patricia Arquette
Release: 2024-11-02 16:51:30
Original
300 people have browsed it

Is there a built-in JavaScript Function to Convert Color Names to Hex Codes?

JavaScript Function to Convert Color Names to Hex Codes

Question:

Exists a built-in JavaScript function for converting color names into their hexadecimal representations, such as converting 'white' to '#FFFFFF'?

Answer:

No, JavaScript doesn't provide such a built-in function. However, utilizing external resources, it's possible to create a custom function:

<code class="javascript">function colourNameToHex(colour) {
  var colours = {
    "aliceblue": "#f0f8ff",
    "antiquewhite": "#faebd7",
    "aqua": "#00ffff",
    "aquamarine": "#7fffd4",
    "azure": "#f0ffff",

    // ... (other color names and hex codes)

    "yellow": "#ffff00",
    "yellowgreen": "#9acd32"
  };

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

  return false;
}</code>
Copy after login

This function uses a pre-defined object containing color names and their corresponding hex codes. By passing a color name (e.g., 'white') into the function, you can retrieve its hex code (e.g., '#FFFFFF'). If the given color name isn't found, the function returns false.

The above is the detailed content of Is there a built-in JavaScript Function to Convert Color Names to Hex Codes?. 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