convert rgb value in hexadecimal system

Solutions on MaxInterview for convert rgb value in hexadecimal system by the best coders in the world

showing results for - "convert rgb value in hexadecimal system"
Eric
22 Nov 2016
1    function convertRgb(rgb) {
2  // This will choose the correct separator, if there is a "," in your value it will use a comma, otherwise, a separator will not be used.
3  var separator = rgb.indexOf(",") > -1 ? "," : " ";
4
5
6  // This will convert "rgb(r,g,b)" into [r,g,b] so we can use the "+" to convert them back to numbers before using toString 
7  rgb = rgb.substr(4).split(")")[0].split(separator);
8
9  // Here we will convert the decimal values to hexadecimal using toString(16)
10  var r = (+rgb[0]).toString(16),
11    g = (+rgb[1]).toString(16),
12    b = (+rgb[2]).toString(16);
13
14  if (r.length == 1)
15    r = "0" + r;
16  if (g.length == 1)
17    g = "0" + g;
18  if (b.length == 1)
19    b = "0" + b;
20
21  // The return value is a concatenation of "#" plus the rgb values which will give you your hex
22  return "#" + r + g + b;
23}
24