0

I have a RGBA color in this format:

RGBA:1.000000,0.003922,0.003922,0.003922

How can I separate each value from this string such as:

var alpha = 1.000000;
var red = 0.003922;
var green = 0.003922;
var blue = 0.003922;

I want to do this in javascript.

3
  • slice then split then map Commented Mar 14, 2014 at 12:13
  • @Anni - Ive replaced "jQuery" with "javascript" in both the title and question. The reason is that this is not a task that requires jQuery - it's vanilla javascript stuff. Commented Mar 14, 2014 at 12:15
  • Or a little more specifically: str.slice(5).split(',').map(Number) Commented Mar 14, 2014 at 12:18

1 Answer 1

4

There is no need to use jQuery. It is rather straightforward JavaScript operation. The easiest way is to use String.prototype.split() method:

var rgba = '1.000000,0.003922,0.003922,0.003922'.split(',');

console.log(rgba[0]);  // "1.000000"
console.log(rgba[1]);  // "0.003922"
console.log(rgba[2]);  // "0.003922"
console.log(rgba[3]);  // "0.003922"

To get numbers instead of strings you may use parseFloat() or a shortcut + trick:

var red = parseFloat(rgba[0]);  // 1.000000
var green = +rgba[1];           // 0.003922

If your string contains extra data you may either first remove it with replace():

var str = 'RGBA:1.000000,0.003922,0.003922,0.003922'.replace('RGBA:', ''),
    rgba = str.split(',');

or use regular expression to match numbers:

var rgba = 'RGBA:1.000000,0.003922,0.003922,0.003922'.match(/\d+\.\d+/g);
>> ["1.000000", "0.003922", "0.003922", "0.003922"]
Sign up to request clarification or add additional context in comments.

14 Comments

Might be worth throwing the parseFloat bit into your answer - looks like the OP wanted numerics rather than strings
original string is RGBA:1.000000,0.003922,0.003922,0.003922
@Jamiec Thanks for the catch. I have added it to the answer.
Another one - slice out the RGBA from the start of the string.
what about the letters RGBA: in the original string
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.