Ryan Peschel Ryan Peschel - 1 year ago 62
HTML Question

Get a color component from an rgb string in Javascript?

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


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?


Answer Source

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, '')




["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(',');