JAVASCRIPT

Extracting Hex Color Codes from Text

A regex pattern to efficiently find and extract standard 3-digit and 6-digit hexadecimal color codes (e.g., #FFF, #AABBCC) from any string.

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

// Example usage:
const text = "The colors are #F00, #336699, and also #abc for a quick fix. Invalid #FFG.";
console.log(extractHexColors(text)); // ["#F00", "#336699", "#abc"]

const anotherText = "Background: #123456; Text: #DEF;";
console.log(extractHexColors(anotherText)); // ["#123456", "#DEF"]
How it works: This JavaScript function uses a global regular expression to find and extract all occurrences of valid hexadecimal color codes within a given text. It specifically matches both shorthand (`#RGB`) and full (`#RRGGBB`) formats, ensuring that the characters are valid hexadecimal digits and that the code is properly delimited by a word boundary.

Need help integrating this into your project?

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

Hire DigitalCodeLabs