Reputation: 152
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.
Upvotes: 0
Views: 82
Reputation: 145478
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"]
Upvotes: 4