Convertire un colore da RGB a esadecimale con jQuery

Nel tutorial di oggi imparerete come creare una funzione che converte un colore RGB in esadecimale utilizzando jQuery.

 
function rgb2hex(rgb) {
 //convert rgb value to hex
 rgb = rgb.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+))?\)$/);
 function hex(x) {
  return ("0" + parseInt(x).toString(16)).slice(-2);
 }
 return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}
 
//example get background color with jQuery
var bgcolor=rgb2hex($('body').css('background-color'));