最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can i get the red green and blue values from an rgbrgba string? - Stack Overflow

programmeradmin7浏览0评论

If I have the string rgba(111,222,333,0.5) how can i extract the individual colours from the string, i.e.

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

I would like to be able to use a neat clean solution for this so I am assuming a regular expression would be best?

If I have the string rgba(111,222,333,0.5) how can i extract the individual colours from the string, i.e.

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

I would like to be able to use a neat clean solution for this so I am assuming a regular expression would be best?

Share Improve this question edited Sep 10, 2012 at 15:55 Selvakumar Arumugam 79.8k15 gold badges121 silver badges137 bronze badges asked Sep 10, 2012 at 15:53 JaiJai 2,2046 gold badges26 silver badges38 bronze badges
Add a ment  | 

6 Answers 6

Reset to default 12

I'd avoid regex for a predictable string, and suggest:

// assigning the rgb() colour to a variable:
var colorString = "rgba(111,222,333,0.5)",

    // using String.prototype.substring() to retrieve
    // the substring between the indices of the opening
    // and closing parentheses:
    colorsOnly = colorString.substring(
        // here we find the index of the opening
        // parenthesis, and add 1 to that index
        // so that the substring starts after that
        // parenthesis:
        colorString.indexOf('(') + 1,

        // and terminating the substring at the
        // index of the closing parenthesis:
        colorString.lastIndexOf(')')
      // here we split that substring on occurrence
      // of a ma followed by zero or more white-
      // space characters:
      ).split(/,\s*/),

    // String.prototype.split() returns an Array,
    // here we assign those Array-elements to the
    // various colour-, or opacity-, variables:
    red = colorsOnly[0],
    green = colorsOnly[1],
    blue = colorsOnly[2],
    opacity = colorsOnly[3];

JS Fiddle demo.

Or, given that you want an object returned:

var colorString = "rgba(111,222,333,0.5)",
  colorsOnly = colorString.substring(colorString.indexOf('(') + 1, colorString.lastIndexOf(')')).split(/,\s*/),
  // here we initialise an empty Object:
  ponents = {};
// here we assign the Array-elements to the
// named properties of that Object:
ponents.red = colorsOnly[0];
ponents.green = colorsOnly[1];
ponents.blue = colorsOnly[2];
ponents.opacity = colorsOnly[3];

console.log(colorsOnly, ponents);

JS Fiddle demo.

Edited to use more contemporary JavaScript:

const colorString = "rgba(111,222,333,0.5)",
  // here we use destructuring assignment to assign the returned Array-elements
  // - in respective order - to the named variables:
  [red, green, blue, opacity] = colorString.substring(colorString.indexOf('(') + 1, colorString.lastIndexOf(')')).split(/,\s*/),
  // passing the variables into the Object Literal; in this instance
  // we're passing in the variables which are the literal name of the
  // properties they define and which also contain the relevant value:
  colorObject = {
    red,
    green,
    blue,
    opacity
  };
console.log(red, green, blue, opacity, colorObject);

References:

  • Array.prototype.indexOf().
  • Destructuring assignment.
  • String.prototype.split().
  • String.prototype.substring().

The Regex for this would be:

^rgba\(([^,]+),([^,]+),([^,]+),([^,]+)\)$

Javascript code:

var regex = /^rgba\(([^,]+),([^,]+),([^,]+),([^,]+)\)$/g; 
var input = "rgba(111,222,333,0.5)"; 
if(regex.test(input)) {
  var matches = input.match(regex);
  for(var match in matches) {
    alert(matches[match]);
  } 
} else {
  alert("No matches found!");
}

You may want to trim the matches and/or convert the values to numbers to get the required RGBA values in JavaScript.

Play with this at RegexHero

If you wanna handle spaces between parameters in the regex itself, it may start looking ugly like this:

^rgba\(\s*([^,\s]+)\s*,\s*([^,\s]+)\s*,\s*([^,\s]+)\s*,\s*([^,\s]+)\s*\)$

making to david more simpler and expainatory

 var colorString = "rgba(111,222,333,0.5)";
 var colorsOnly = colorString.split(")"); //gives "rgba(111,222,333,0.5" at index 0
 var colorsOnly = colorString[0].split("(");   //gives "111,222,333,0.5 at index 1
 var colorsOnly = colorString[1].split(","); 

gives "111" at [0], "222" at [1], "333" at [2] and "0.5" at [3] but NOTE: all of these have string data types as all of these are subStrings.

red = parseInt(colorsOnly[0]);
green = parseInt(colorsOnly[1]);
blue = parseInt(colorsOnly[2]);
opacity = parseFloat(colorsOnly[3]);

use parseInt() and parseFloat() methods to convert the strings into integer and float resp.

For Ahmed Bilal's answer, I have something to correct. If I am wrong, please also feel free to correct me! :)

It should be:

    var colorsOnly = colorString.split(")");
    var colorsOnly = colorString.split("(");
    var colorsOnly = colorsOnly[1].split(",");      

Notice the change of the fourth sentence. Since ColosOnly from the third sentence has represented the outes after the "(" splitting. So I think it should be colorsOnly[1] in the third sentence. I tried it on myself and got proved.

Again, if I am wrong, please also feel free to correct me! :)

This is another solution.

const rgbaStrToValues = function( rgba ) {
    const realNumPattern = '([+-]?\\d*\\.?\\d+)';
    const rgbaPattern = `rgba?\\(` +
        ` *${ realNumPattern } *, *${ realNumPattern } *,` +
        ` *${ realNumPattern } *(?:, *${ realNumPattern } *)?\\)`;
    const regexp = new RegExp( rgbaPattern );
    const result = regexp.exec( rgba );
    if ( ! result ) { return; }

    const { 1: red, 2: green, 3: blue, 4: alpha } = result;
    if ( ! ( red && green && blue ) ) { return; }

    const { min, max } = Math;
    return {
        red  : max( min( Number( red ), 255 ), 0 ),
        green: max( min( Number( green ), 255 ), 0 ),
        blue : max( min( Number( blue ), 255 ), 0 ),
        alpha: alpha ? max( min( Number( alpha ), 1 ), 0 ) : 1,
    };
};

rgbaStrToValues( 'rgba( 111, 222, 333, 0.5 )' );

I wrote the description of this code in Japanese at

  • 'rgb[a](R, G, B[, A])' を正規表現で処理して、各値をメンバーとしてもつオブジェクトを返す関数。 - Qiita

if it's always in rgba format you can do something like this:

var str = 'rgba(111,222,333,0.5)'

var red = str.substr(5,3);
var green = str.substr(9,3);
var red = str.substr(13,3);
发布评论

评论列表(0)

  1. 暂无评论