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
Try this regex:
/rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/
It will capture the r value into $1, the g value into $2, and the b value into $3
I use this one: rgb\(\s*(?:(?:\d{1,2}|1\d\d|2(?:[0-4]\d|5[0-5]))\s*,?){3}\)$
rgb
at the end we have {3}
it means we will checks conditions from below 3 times
\d{1,2}
if value inside have only 1 or 2 symbols - check if there are digits
1\d\d
if value inside have 3 digits and first one is equals to 1
and rest of them are digits
2(?:[0-4]\d|5[0-5])
if value inside have 3 digits and first one is equals to 2
then
?:[0-4]\d
if second symbol is in range of 0-4
the third one should any digit5[0-5]
if second symbol is equals to 5
then third symbol should be digit from range 0-5
Try this. A regex within the range 0 - 255.
rgb\((( *0*([1]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5]) *),){2}( *0*([1]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5]) *)\)
Debuggex Demo
^(\\d{1,2}|[1][0-9][0-9]|[2][0-5][0-5]);(\\d{1,2}|[1][0-9][0-9]|[2][0-5][0-5]);(\\d{1,2}|[1][0-9][0-9]|[2][0-5][0-5])$
format x;x;x
where x
is a number between 0
(included) and 255
(included)
Here is some example code that should do approximately what you need or set you in the right direction:
var color = 'rgb(255, 15, 120)';
var matchColors = /rgb\((\d{1,3}), (\d{1,3}), (\d{1,3})\)/;
var match = matchColors.exec(color);
if (match !== null) {
document.write('Red: ' + match[1] + ' Green: ' + match[2] + ' Blue: ' + match[3]);
}
You can see it in action here: http://jsfiddle.net/xonev/dRk8d/
Typescript solution:
interface RGB {
r: number,
g: number,
b: number
}
const str2rgb = (color: string): RGB => {
const rgbSubset = color
.split('(')
.pop()
?.split(')')
.shift()
?.split(',')
.slice(0, 3)
.map(Number);
if (rgbSubset && rgbSubset.length === 3) {
const [r, g, b] = rgbSubset;
return {r, g, b};
}
throw new Error(`Invalid color = ${color}`);
};