1

I wanted to convert box-shadow:rgb(255, 255, 255) 10px 10px 0px , rgb(0, 0, 0) 10px 10px 0px, rgb(255, 255, 255) 10px 10px 0px to box-shadow:#FFF 10px 10px 0px , #000 10px 10px 0px, #FFF 10px 10px 0px

Can any one help me for this.

Thanks in advance.

  • Do you want a script that does this, or do it manually and just don't know how? – padarom Apr 08 '14 at 12:50
  • I wanted to know if there is any API / script for converting the box-shadow from RGB to HEX – user3492546 Apr 08 '14 at 12:52
  • possible duplicate of [RGB to Hex and Hex to RGB](http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb) – Tushar Gupta - curioustushar Apr 08 '14 at 12:55
  • Actually I am getting a long string with multiple drop shadow values. Instead of using regEx and filtering out the multiple rgb values from the entire string, wanted to know if there is any already existing javascript code snippet or any DOM API's... – user3492546 Apr 08 '14 at 12:58

3 Answers3

0

to convert RGB to hex you need to find the different source for each r, g, and b find the hex for each and every source based on the length

function findMyHex(get) {
    var hex = get.toString(16);
    return hex.length == 1 ? "0" + hex : hex;
}

function tohex(r, g, b) {
    return "#" + findMyHex(r) + findMyHex(g) + findMyHex(b);
}

console.log(tohex(255, 255, 255)); 

hope this will help you.

Santhosh Kumar
  • 190
  • 3
  • 10
0

In javascript you can use .toString(base) to convert a number into another base (in this case it's base 16 -> hexadecimal).

An example:

var r = 255;
var g = 128;
var b = 219;
var hex = "#" + r.toString(16) + g.toString(16) + b.toString(16);
// hex = #ff80db

You just need to run something like this through your desired text in a loop and replace every occurence.

padarom
  • 3,529
  • 5
  • 33
  • 57
0

Maybe overkill,

function rgbToHex(str_rgb, withShorts, b) {
    var r, g, h;
    if (arguments.length < 3) {
        withShorts = !!withShorts;
        h = str_rgb.match(/rgba?\( *(\d+) *, *(\d+) *, *(\d+)/);
        r = +h[1];
        g = +h[2];
        b = +h[3];
    } else {
        r = str_rgb | 0, g = withShorts | 0, b = b | 0;
        withShorts = !!arguments[3];
    }
    r = r.toString(16), g = g.toString(16), b = b.toString(16);
    r = ('0' + r).slice(-2), g = ('0' + g).slice(-2), b = ('0' + b).slice(-2);
    if (withShorts) {
        if (r[0] === r[1])
            if(g[0] === g[1])
                if (b[0] === b[1])
                    return '#' + (r[0] + g[0] + b[0]).toUpperCase();
    }
    return '#' + (r + g + b).toUpperCase();
}

Now have

// ints
rgbToHex(255, 255, 255);       // "#FFFFFF"
rgbToHex(255, 255, 255, true); // "#FFF"
// strings
rgbToHex('rgb(255, 255, 255)');       // "#FFFFFF"
rgbToHex('rgb(255, 255, 255)', true); // "#FFF"
// ignores alpha
rgbToHex('rgba(255, 255, 255, 0)'); // "#FFFFFF"
// does padding
rgbToHex(1, 10, 14); // "#010A0E"
Paul S.
  • 64,864
  • 9
  • 122
  • 138