Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
128
rated 0 times [  132] [ 4]  / answers: 1 / hits: 45844  / 12 Years ago, sun, june 10, 2012, 12:00:00

I'm using Javascript and Canvas to make a painting app and was using strings in this format to designate chosen colors:



rgb(255,0,0)



Because the canvas context fillStyle property takes in strings of that format.



However, I now need to obtain individual components from this string and was wondering if there was a way to do it without messy string manipulation. Possibly some built in way to convert that string to a sort of color object and then access its r, g, and b components?



Thanks.


More From » html

 Answers
79

NOTE - We're all on board with the regex ate my brains and kicked my dog attitude, but the regex version just seems the better method. My opinion. Check it out.



Non-regex method:



var rgb = 'rgb(200, 12, 53)';

rgb = rgb.substring(4, rgb.length-1)
.replace(/ /g, '')
.split(',');

console.log(rgb);


http://jsfiddle.net/userdude/Fg9Ba/



Outputs:



[200, 12, 53]


Or... A really simple regex:



EDIT: Ooops, had an i in the regex for some reason.



var rgb = 'rgb(200, 12, 53)';

rgb = rgb.replace(/[^d,]/g, '').split(',');

console.log(rgb);


http://jsfiddle.net/userdude/Fg9Ba/2


[#85007] Saturday, June 9, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brennanm

Total Points: 510
Total Questions: 103
Total Answers: 95

Location: Nicaragua
Member since Tue, Dec 8, 2020
4 Years ago
;