Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Regular Expression for rgb values

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:

var color = rgb(255, 85, 120);

/// My Regex ///
var rRegex = /^rgb\(\d{3}/;  // Which actually gives me an array of two strings...ugh
var gRegex = ;
var bRegex = ;

var r = color.match(rRegex);
var g = color.match(gRegex);
var b = color.match(bRegex);

I'm just looking to have:

/// // I think I can pull these off by Starts With and Ends With anchors... ///
r = 'From "(" to "," ';
g = 'From "," to "," ';
b = 'From "," to ")" ';

I'm trying to make also make it so that the regex can take either 1, 2, or 3 numbers, as the values go from 0 - 255. Thanks for any help!

like image 275
cja Avatar asked Mar 06 '12 14:03

cja


1 Answers

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/

like image 138
Steven Oxley Avatar answered Sep 28 '22 22:09

Steven Oxley