'Regexp Matching Hex Color Syntax (and Shorten form)
Well, I'm pretty new on regex and in particular on JavaScript regexp.
I'm looking for making a regexp that match the hex color syntax (like #34ffa6)
Then I looked at the w3school page: Javascript RegExp Object
Then that's my regexp:
/^#[0-9a-f]{6}/i
It seems to work but, if I want it to match also the "short hex color syntax" form? (like #3fa), it's possible? I've tried using the character | but maybe I'm wrong with the syntax.
Solution 1:[1]
Try this :
/^#([0-9a-f]{6}|[0-9a-f]{3})$/i
[0-9a-f]{6} = 6 characters
[0-9a-f]{3} = 3 characters
$ = end
Solution 2:[2]
this should work
/#[0-9a-f]{6}|#[0-9a-f]{3}/gi
and for trying out regular expressions on the fly and learning it you can use this site http://gskinner.com/RegExr/
Solution 3:[3]
You might want to incorporate 4 and 8 digit hex for #RGBA and #RRGGBBAA. I am doing this in a different setting where I'm using match() and split() to generate arrays. I could not get all the variations posted by @rodneyrehm to work with the g flag and match, but the first (and most verbose) solution works if I list the character count in high to low order: 8, 6, 4, 3.
let rx = /(?:#)[0-9a-f]{8}|(?:#)[0-9a-f]{6}|(?:#)[0-9a-f]{4}|(?:#)[0-9a-f]{3}/ig
let s = "123 #AA22CC 100% #12F abc #A2Cd #aa11cc44 test 236px";
let arr = s.match(rx); // arr == ["#AA22CC", "#12F", "#A2Cd", "#aa11cc44"]
The MDN docs say that (?:#) should forget "#", but it does not, and (?=#) simply fails. What am I misunderstanding?
My final goal is to include the other numeric values in the array returned from match(). I'm almost there...
Solution 4:[4]
The possible Hex Colors are -
| Format | Example |
|---|---|
| #RGB | #F00 |
| #RGBA | #F005 |
| #RRGGBB | #FF7C00 |
| #RRGGBBAA | #FF7C0016 |
Regexp to match color without alpha
let regex = /^#([A-F0-9]{3}|[A-F0-9]{6})$/i
Regexp to match color with alpha
let regex = /^#([A-F0-9]{3,4}|[A-F0-9]{6}|[A-F0-9]{8})$/i
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Manse |
| Solution 2 | Saket Patel |
| Solution 3 | jamess |
| Solution 4 | Zawad |
