Match hex color codes

easy

By - Aman Pareek

Last Updated - 15/09/2024

Problem Statement

Alia is a web developer working on a project that involves analyzing stylesheets and design documents. She needs to extract hex color codes from various text sources, such as CSS files and HTML documents. The color codes can appear in different formats:

  • Full hex format: #RRGGBB

  • Short hex format: #RGB

Objective:

Develop a JavaScript function that helps Alia efficiently extract and standardize hex color codes from a block of text. The function should handle both full and short formats and return a consistent array of color codes.

Example 1

Input: string = "The colors used are #ff5733 for the header, #33cc99 for the footer, and #abc for the background."

Output: ["#ff5733", "#33cc99", "#aabbcc"]

Example 2

Input: string = " The new color scheme includes #f00 for alerts, #0f0 for success, and #00f for links. Avoid using invalid colors like #1234567 or #xyz. Ensure you use the correct format."

Output: ["#f00", "#0f0", "#00f"]

Solution 1: Match hex color codes using regex

function extractHexColorCodes(text) {
    // Define regex patterns for both full and short hex color codes
    const hexColorRegex = /#(?:[0-9a-fA-F]{6}|[0-9a-fA-F]{3})\b/g;

    // Find all matches in the text
    const matches = text.match(hexColorRegex);

    // If matches are found, expand short format codes to full format
    if (matches) {
        return matches.map(color => {
            // Expand short format #RGB to #RRGGBB
            if (color.length === 4) {
                return `#${color[1]}${color[1]}${color[2]}${color[2]}${color[3]}${color[3]}`;
            }
            return color;
        });
    }

    // Return an empty array if no matches are found
    return [];
} 

const string1 = "The colors used are #ff5733 for the header, #33cc99 for the footer, and #abc for the background.";
extractHexColorCodes(string1);  //output: ["#ff5733", "#33cc99", "#aabbcc"] 

const string2 = " The new color scheme includes #f00 for alerts, #0f0 for success, and #00f for links. Avoid using invalid colors like #1234567 or #xyz. Ensure you use the correct format.";
extractHexColorCodes(string2);  //output: ["#f00", "#0f0", "#00f"] 

Frequently asked questions

  1. What hex color formats does the function handle?

    The function handles both full format (#RRGGBB) and short format (#RGB) hex color codes.

  2. How does the function handle short format codes?

    The function expands short format codes (#RGB) into the full format (#RRGGBB) by duplicating each hexadecimal digit.

  3. Can the function handle invalid color codes?

    Yes, the function ignores invalid color codes and only returns valid hex color codes.

  4. What if the color codes have different delimiters or formats?

    The current regex pattern assumes hex codes start with # and are followed by valid hexadecimal digits. For other formats or delimiters, the pattern may need adjustment.

  5. How can I test the function with various inputs?

    Test the function by providing different blocks of text that include a mix of valid and invalid hex color codes to ensure accurate extraction and validation.