Anni
Anni

Reputation: 152

seperate Red Green Blue value of rgba Colur value

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

Upvotes: 3

Views: 938

Answers (4)

Gaurang Tandon
Gaurang Tandon

Reputation: 6753

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

Upvotes: 0

Ankur Aggarwal
Ankur Aggarwal

Reputation: 3101

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];

Upvotes: 0

dandavis
dandavis

Reputation: 16726

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.

Upvotes: -1

Praveen
Praveen

Reputation: 56501

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.

Upvotes: 2

Related Questions