JAVASCRIPT

Extracting Hex Color Codes (3 or 6 Digits)

Efficiently find and extract all 3-digit and 6-digit hexadecimal color codes (e.g., #FFF, #00FFCC) from any text string using a powerful JavaScript regular expression.

function extractHexColors(text) {
  // Matches 3-digit or 6-digit hex color codes, preceded by '#'
  const hexColorRegex = /#([0-9a-fA-F]{3}){1,2}\b/g;
  const matches = text.match(hexColorRegex);
  return matches || [];
}

const content = "The background is #FFF, text is #00FFCC, and a border might be #333, but not #ABCDEFG or just #12.";
const colors = extractHexColors(content);

console.log("Extracted Hex Colors:", colors);
/*
Example Output:
Extracted Hex Colors: [ '#FFF', '#00FFCC', '#333' ]
*/
How it works: This JavaScript function `extractHexColors` uses a global regular expression `/#([0-9a-fA-F]{3}){1,2}\b/g` to find all occurrences of hexadecimal color codes within a given text. The pattern looks for a hash `#` followed by either three `([0-9a-fA-F]{3})` or six `([0-9a-fA-F]{3}){2}` hexadecimal characters (0-9, a-f, A-F). The `{1,2}` quantifier allows for both 3-digit and 6-digit patterns, and `\b` ensures a word boundary. The `g` flag ensures all matches are found.

Need help integrating this into your project?

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

Hire DigitalCodeLabs