rgb(a) to hex

by SamHasler

HTML

Convert RGB/RGBA to hex:<br>
(opacity of rgba is ignored)<br>
<input id="re" type="text" value="\s*R(\d+)\s*G(\d+)\s*B(\d+)\s*"><br>
<input id="newSubStr" type="text" value="$1 $2 $3"><br>
<input id="color" type="text" value="R20 G68 B120"> <button>Convert</button><br>
<br>
Result <input class="result" value="14 44 78">

<pre>
R20 G68 B120
\s*R(\d+)\s*G(\d+)\s*B(\d+)\s*

rgba(34, 34, 34, 1)
^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?.*

#$1$2$3
$1 $2 $3
</pre>

CSS

body { padding: 20px; background: #222; color: #ddd; }

Babel + JSX

//Function to convert hex format to a rgb color
var dec2hex = (d) => ("0" + parseInt(d,10).toString(16)).slice(-2).toUpperCase()
  , newSubStr = "#$1$2$3"
  , rgb2hexReplacer = ((match, r, g, b, offset, string) => { //console.log([match,r,g,b,string]);
  return (""+dec2hex(r)+dec2hex(g)+dec2hex(b)
         ).replace(/^(..)(..)(..)$/,newSubStr)
    })
  ;

function rgb2hex(rgb,reStr){
 var rgbmatch = rgb.match(new RegExp(reStr,'i'));
 return (rgbmatch && rgbmatch.length === 4) ?
   (""+rgb).replace(new RegExp(reStr,'i'),rgb2hexReplacer)
   : '' ;
}

$('button').click(function(){
    newSubStr = $('#newSubStr').val();
    var hex = rgb2hex( $('#color').val(), $('#re').val() );
    $('.result').val( hex );
});