Click to See Complete Forum and Search --> : Hexadecimal digits
cmyers
01-22-2003, 01:12 PM
Again, I'm a JS newbie trying to get by and have to write a function that does the followings:
function isWebColor(v)
where v can be anything. return true if it is a
series of 6 hexadecimal digits (may or may not have #
in front of them). otherwise return false.
So, if v were 123456, then it would be true
if v were 12345, it wouldn't, because there are only 5
digits. Also, since they are hex digits, a-e are
allowed as well, and it doesn't matter if they're
upper case or lower.
v as "#3366AA" would return true.
v as "3366LL" would return false.
Could anyone start me in the right direction to create such a function? Any help would be appreciated.
Thank you.
Cathy
jeffmott
01-22-2003, 02:09 PM
function isWebColor(v) {
// remove optional hash mark
v = v.replace(/^#?/, "");
// if not in 3 (ABC) or 6 (AABBCC) digit format, return false
if (v.length != 3 && v.length != 6)
return false;
// if v contains a non-hex character, return false
if (v.match(/[^0-9a-f]/i))
return false;
// passed all tests, return true
return true;
}
jeffmott
01-22-2003, 02:16 PM
Also, here's something else I put together when I misunderstood the question. I changed the function name to reflect its purpose.
function isWebSafeColor(v) {
v = v.replace(/^#?/, "");
if (v.length == 3) {
if (v.match(/[^0369cf]/i))
return false;
}
else if (v.length == 6) {
if (!v.match(/^([0369cf])\1([0369cf])\2([0369cf])\3$/i))
return false;
}
else return false;
return true;
}
Charles
01-22-2003, 02:23 PM
<script type="text/javascript">
<!--
String.prototype.isWebColor = function () {return /^#?[a-f0-9]{6}$/i.test(this) || /^#?[a-f0-9]{3}$/i.test(this)}
document.write('f00'.isWebColor());
// -->
</script>
1 - Three character colours are also valid. See http://www.w3.org/TR/REC-CSS2/syndata.html#color-units.
2 - This method is sophisticated enough that if you turn this in as homework then your teacher will know that you cheated.
Dan Drillich
01-22-2003, 02:49 PM
I slightly modified Charles code to make the pound sign optional -
<script type="text/javascript">
<!--
String.prototype.isWebColor = function () {return /^[#]{0,1}[a-f0-9]{6}$/i.test(this) ||
/^[#]{0,1}[a-f0-9]{3}$/i.test(this)}
document.write('D00'.isWebColor());
// -->
</script>
Cheers,
Dan
cmyers
01-22-2003, 03:09 PM
Thanks for all your responses ... I will test them out!
Cathy :)
Charles
01-22-2003, 03:09 PM
The pound sign is optional with my method. That's what those question marks are there for.
Dan Drillich
01-22-2003, 03:12 PM
You are right Charles - I missed it.