我有这种格式的RGBA颜色:
RGBA:1.000000,0.003922,0.003922,0.003922
如何将每个值与此字符串分开,例如:
var alpha = 1.000000;
var red = 0.003922;
var green = 0.003922;
var blue = 0.003922;
我想在javascript中执行此操作。
答案 0 :(得分:4)
没有必要使用jQuery。这是一个相当简单的JavaScript操作。最简单的方法是使用String.prototype.split()
方法:
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"
要获取数字而不是字符串,您可以使用parseFloat()
或快捷+
技巧:
var red = parseFloat(rgba[0]); // 1.000000
var green = +rgba[1]; // 0.003922
如果您的字符串包含额外数据,您可以先使用replace()
删除它:
var str = 'RGBA:1.000000,0.003922,0.003922,0.003922'.replace('RGBA:', ''),
rgba = str.split(',');
或使用regular expression来匹配数字:
var rgba = 'RGBA:1.000000,0.003922,0.003922,0.003922'.match(/\d+\.\d+/g);
>> ["1.000000", "0.003922", "0.003922", "0.003922"]