JAVASCRIPT

Extract All CSS Hex Color Codes from a String

A JavaScript regex snippet to accurately find and extract all 3-digit and 6-digit CSS hexadecimal color codes (e.g., #FFF, #C0C0C0) from any text.

function extractHexColors(text) {
  const hexColorRegex = /#([a-fA-F0-9]{3}){1,2}\b/g;
  return text.match(hexColorRegex) || [];
}

// Example usage:
// const cssString = "color: #FFF; background-color: #C0C0C0; border: 1px solid #336699;";
// console.log(extractHexColors(cssString)); // ["#FFF", "#C0C0C0", "#336699"]
// const invalidColors = "font: #ABCDE; text: #1234567;";
// console.log(extractHexColors(invalidColors)); // []
How it works: This JavaScript function uses the regular expression `/ #([a-fA-F0-9]{3}){1,2}\b/g` to locate hex color codes within a string. It looks for a '#' followed by either three or six hexadecimal characters (0-9, a-f, A-F). The `\b` ensures a word boundary, preventing partial matches within other strings, and the `g` flag ensures all matches are returned in an array.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs