[英]How to get specific part of a strings from a string using javascript?
I have a RGBA color in this format: 我有以下格式的RGBA颜色:
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. 我想用javascript做。
There is no need to use jQuery. 无需使用jQuery。 It is rather straightforward JavaScript operation.
这是相当简单的JavaScript操作。 The easiest way is to use
String.prototype.split()
method: 最简单的方法是使用
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"
To get numbers instead of strings you may use parseFloat()
or a shortcut +
trick: 要获取数字而不是字符串,可以使用
parseFloat()
或快捷方式+
技巧:
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()
: 如果您的字符串包含额外的数据,则可以先使用
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"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.