JAVASCRIPT
Validate and Extract Hex Color Codes
A JavaScript snippet to validate if a string is a valid 3-digit or 6-digit hexadecimal color code and extract it, useful for CSS and UI checks.
function getHexColor(text) {
// Matches #RGB or #RRGGBB format
const hexColorRegex = /#([a-fA-F0-9]{3}){1,2}\b/;
const match = text.match(hexColorRegex);
return match ? match[0] : null;
}
// Example Usage:
console.log(getHexColor("The color is #FF00FF.")); // #FF00FF
console.log(getHexColor("Background: #abc;")); // #abc
console.log(getHexColor("Not a color code.")); // null
console.log(getHexColor("Color is #12345.")); // null (invalid length)
How it works: The `getHexColor` JavaScript function utilizes a regular expression to find and extract valid hexadecimal color codes (e.g., `#RRGGBB` or `#RGB`) from a given string. It returns the first matched hex color code found, including the '#' prefix, or `null` if no valid hex color code is present.