如果我有字符串rgba(111,222,333,0.5),如何从字符串中提取各个颜色,即

red => 111
green => 222
blue => 333
opacity => 0.5


我希望能够为此使用整洁的清洁解决方案,所以我假设正则表达式将是最佳选择?

最佳答案

我会避免使用正则表达式作为可预测的字符串,并建议:

var colorString = "rgba(111,222,333,0.5)",
    colorsOnly = colorString.substring(colorString.indexOf('(') + 1, colorString.lastIndexOf(')')).split(/,\s*/),
    red = colorsOnly[0],
    green = colorsOnly[1],
    blue = colorsOnly[2],
    opacity = colorsOnly[3];


JS Fiddle demo

或者,假设您要返回一个对象:

var colorString = "rgba(111,222,333,0.5)",
    colorsOnly = colorString.substring(colorString.indexOf('(') + 1, colorString.lastIndexOf(')')).split(/,\s*/),
    components = {};
components.red = colorsOnly[0];
components.green = colorsOnly[1];
components.blue = colorsOnly[2];
components.opacity = colorsOnly[3];

console.log(colorsOnly, components);​


JS Fiddle demo

关于javascript - 如何从rgb/rgba字符串获取红色绿色和蓝色值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12355212/

10-12 20:36