3

I'hv rgba value in this format RGBA(205,31,31,1) and I want to separate each red, green, blue and alpha value for further processing how can I achieve it using jQuery; so the output looks like

red = 205
green = 31
blue = 31
alpha =1
Praveen
  • 55,303
  • 33
  • 133
  • 164
Anni
  • 142
  • 2
  • 16
  • 1
    Use a regular expression to target everything inside of `RGBA( )`. Then take that value, split it by `","`. Try that, and come back with specific problems you're having. This could probably even be done with one regular expression and not have to split – Ian Mar 13 '14 at 05:03

4 Answers4

2

To get these values from a string variable is easy with the following answer so you don't need jQuery

With the help of regex, you can easily achieve it like

var color = "RGBA(205,31,31,1)";
var regExp = /\(([^)]+)\)/;  // get the values within ()
var matches = regExp.exec(color);
var splits = matches[1].split(',');
alert("red: " + splits[0] + "green: " + splits[1]+ "blue: "+ splits[2]+ "alpha: " +splits[3] );

JSFiddle

However to get the rgba value from an element you can use jQuery's css method.

Community
  • 1
  • 1
Praveen
  • 55,303
  • 33
  • 133
  • 164
0
var string = "RGBA(205,31,31,1)";

var colors = [];

string = string.replace(/[rgba\(\)]/gi, '');  // remove unnecessary characters

string = string.split(",");   // split by comma

for(var i = 0;i < string.length; i++){  
    colors.push(parseFloat(string[i], 10));  // parse the integer and push in colors array
}


console.log(colors); // [ 205, 31, 31, 1 ] the values are in RGBA order
Gaurang Tandon
  • 6,504
  • 11
  • 47
  • 84
0

Without Regular Expression:

var colorString = "rgba(111,222,333,0.5)",
    colorsOnly = colorString.substring(colorString.indexOf('(') + 1, colorString.lastIndexOf(')')).split(/,\s*/),
    red = colorsOnly[0],
    green = colorsOnly[1],
    blue = colorsOnly[2],
    opacity = colorsOnly[3];
Ankur Aggarwal
  • 2,993
  • 5
  • 30
  • 56
-1

a simple modern approach:

"RGBA(205,31,31,1)".match(/[\d\.]+/g).map(Number); //==[205, 31, 31, 1]

or if you want an object, it's a bit more work:

"RGBA(205,31,31,1)".match(/[\d\.]+/g).map(Number)
  .reduce(function(a,b,i){  
       a[["red","blue","green","alpha"][i]]=b; 
     return a;  
  }, {}); // ==  {red: 205, blue: 31, green: 31, alpha: 1}

using "".match() is nice because it ignores spaces in-between the numbers and the case of the "rgba" text as well.

dandavis
  • 16,370
  • 5
  • 40
  • 36