Wednesday, February 20, 2013

Check a hex color code using a regular expression

This handy function uses a regular expression to check for a valid 6 or 3-digit hex code beginning with #.

function hexCheck (hex) {
    var re = /^\#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/;
    return re.test(hex); // returns true if this is a valid hex code
}

This can and should be elaborated into another method for regularizing hex codes. ( Adding #, etc )

No comments:

Post a Comment