-1

I would like to know how do I convert "rgb(255, 255, 255)" string format to rgb, like:

var rgb = convert("rgb(255, 255, 255)");

and use it like this:

this.r = rgb.r;
this.g = rgb.g;
this.b = rgb.b;

What I found so far is how to convert to\from hex to rgb.

Thank you

Jacob
  • 3,598
  • 4
  • 35
  • 56

2 Answers2

3

The simpler way I could find:

var convert = function(rgb)
{    
    var s = rgb.replace(/[^\d\s]/g, '').split(' ');

    return {
        r: s[0],
        g: s[1],
        b: s[2]
    };
}

console.log(convert("rgb(255, 255, 255)"));

Fiddle.

This isn't converting anything. Just extracting the information of the string and put into an object.

UPDATE:

For the suggestion of @minmaxavg, for this to work with percent values, just make a slightly change on the regex to this:

/[^\d\s%]/g
DontVoteMeDown
  • 21,122
  • 10
  • 69
  • 105
  • `getComputedStyles` seems to be a better way since this returns *incorrect* results for something like `rgb(50%, 50%, 50%)` – minmaxavg Jan 15 '15 at 11:47
  • 2
    @minmaxavg this depends. I made this answer from the top of head to deal with the OP's example, straight. You answer is good but is far beyond OP requested and much less performatic. Anyway, isn't nice to copy and paste somebody's else answer(even giving its source). – DontVoteMeDown Jan 15 '15 at 11:50
  • @minmaxavg BTW, using this regex `/[^\d\s%]/g` achieves what you suggested, thank you for point that bro. – DontVoteMeDown Jan 15 '15 at 11:53
  • You're welcome. Okay, I won't copy answers from other questions again. Sorry for that..:( – minmaxavg Feb 02 '15 at 04:41
2

You can use a simple regex to macth rgb({number}, {number}, {number}):

function convertRgb(rgb) {
    // results contains e.g. ["rgb(255, 255, 255)", "255", "255", "255"]
    var results = /^rgb\((\d{1,3}), (\d{1,3}), (\d{1,3})\)$/.exec(rgb);
    return {
        r: results[1],
        g: results[2],
        b: results[3],
    };
}

var rgb = convertRgb("rgb(255, 255, 255)");
console.dir(rgb);
Rhumborl
  • 16,349
  • 4
  • 39
  • 45