简体   繁体   中英

How to get specific part of a strings from a string using javascript?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM