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!