I\'m trying to get the individual values of a rgb string. I\'ve been getting close, but I\'m just hitting a wall. I\'m looking to do something like this:
v
function rgb(value) {
if (typeof value !== 'string') {
return false;
}
return value.match(new RegExp('^rgb\\((25[0-5]|2[0-4][0-9]|1[0-9]?[0-9]?|[1-9][0-9]?|[0-9]), ?(25[0-5]|2[0-4][0-9]|1[0-9]?[0-9]?|[1-9][0-9]?|[0-9]), ?(25[0-5]|2[0-4][0-9]|1[0-9]?[0-9]?|[1-9][0-9]?|[0-9])\\)$')) !== null;
}
function rgba(value) {
if (typeof value !== 'string') {
return false;
}
return value.match(new RegExp('^rgba\\((25[0-5]|2[0-4][0-9]|1[0-9]?[0-9]?|[1-9][0-9]?|[0-9]), ?(25[0-5]|2[0-4][0-9]|1[0-9]?[0-9]?|[1-9][0-9]?|[0-9]), ?(25[0-5]|2[0-4][0-9]|1[0-9]?[0-9]?|[1-9][0-9]?|[0-9]), ?(1|0|0\.[0-9]+)\\)$')) !== null;
}
Examples:
'rgb(255,255,255)' // true
'rgb(255, 255,255)' // true
'rgb(255, 255, 255)' // true
'rgb(0,0,0)' // true
'rgb(255,255,255)' // true
'rgb(256,255,255)' // false, min: 0, max: 255
'rgb(01,1,1)' // false, zero is not accepted on the left, except when the value was exactly 0 (here 0 != 00)
I have come up with this "^(rgb)?\(?([01]?\d\d?|2[0-4]\d|25[0-5])(\W+)([01]?\d\d?|2[0-4]\d|25[0-5])\W+(([01]?\d\d?|2[0-4]\d|25[0-5])\)?)$"
which can validate a whole heap of string variations including:
Given a string is valid rgb, parsing numbers out it is a matter of matching digits:
"rgb(12, 34, 56)".match(/\d+/g); // ["12", "34", "56"]