8

Given a string like #fff443 or #999999

How do I verify that the string has:

  • 7 characters, with the first one being a hash
  • no symbols in the string besides the hash in the beginning
Jelle De Loecker
  • 20,999
  • 27
  • 100
  • 142
TIMEX
  • 259,804
  • 351
  • 777
  • 1,080
  • 1
    there are many ways to check with different structures : see my advanced answer : http://stackoverflow.com/questions/8027423/how-to-check-if-a-string-is-a-valid-hex-color-representation/8027444#8027444 – Royi Namir Jan 15 '12 at 10:05

1 Answers1

23

It seems that you are matching against a css color:

function isValidColor(str) {
    return str.match(/^#[a-f0-9]{6}$/i) !== null;
}

To elaborate:

^ match beginning
# a hash
[a-f0-9] any letter from a-f and 0-9
{6} the previous group appears exactly 6 times
$ match end
i ignore case

qiao
  • 17,941
  • 6
  • 57
  • 46
  • 5
    @RoyiNamir: What doesn't this cover, according to the OP's strict requirements? – Wesley Murch Jan 15 '12 at 10:05
  • @qiao : the fact that he also doesnt know that a hex can be `#aca` – Royi Namir Jan 15 '12 at 10:09
  • 2
    @RoyiNamir: That is beyond the point of the question. The OP is really just validating a string, which happens to contain a 6 digit hex. If the OP cared about `#aca` or `aquamarine` (assuming this is for a color) he would have said so. Read beyond just the question title. – Wesley Murch Jan 15 '12 at 10:12
  • 1
    I recommend to use `/^#[a-f0-9]{6}$/i`.exec(str)`, in case the supplied argument is not a string. – Rob W Jan 15 '12 at 10:23
  • @qiao also next time use test and not match . its much faster. – Royi Namir Jan 15 '12 at 10:36
  • 2
    I would like to add that I appreciate you explaining the regex. Understanding regular expressions is the most difficult part, copy/pasting them is easy :) If everyone did this there would be 80% less questions here about how to write a specific regex. – Wesley Murch Jan 15 '12 at 10:53
  • `/^#[a-f0-9]{6}|#[a-f0-9]{3}$/i` helps if you only need a valid hex color – Hevelson Rosario Feb 17 '21 at 19:46