Skip to content

Instantly share code, notes, and snippets.

@john-yuan
Created April 2, 2019 02:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save john-yuan/267e8cf1f262f2ebae03beb1870b4631 to your computer and use it in GitHub Desktop.
Save john-yuan/267e8cf1f262f2ebae03beb1870b4631 to your computer and use it in GitHub Desktop.
/**
* Convert rgb formatted color string to hash formatted color string
*
* @example
* // @returns #ff00ff
* rgb2hash('rgb(255, 0, 255)');
*
* @param {string} rgbColorStr The rgb formatted color string
* @returns {string} Returns the hash formatted color string
*/
var rgb2hash = function (rgbColorStr) {
var str = '' + (rgbColorStr || '');
var rgb = [];
var r, g, b;
// remove `rgb(`
str = str.replace(/^\s*rgb\s*\(\s*/, '');
// remove `)`
str = str.replace(/\s*\)\s*$/, '');
// spilt by `,`
rgb = str.split(/\s*\,\s*/);
r = (parseInt(rgb[0] || 0) || 0).toString(16);
g = (parseInt(rgb[1] || 0) || 0).toString(16);
b = (parseInt(rgb[2] || 0) || 0).toString(16);
r = r.length < 2 ? ('0' + r) : r;
g = g.length < 2 ? ('0' + g) : g;
b = b.length < 2 ? ('0' + b) : b;
return '#' + r + g + b;
};
/**
* Convert the hash formatted color string to rgb formatted color string
*
* @example
* // Returns rgb(204, 204, 204)
* hash2rgb('#cccccc');
* // Returns rgb(238, 238, 238)
* hash2rgb('#eee');
*
* @param {string} hashColorStr The hash formatted color string
* @returns {string} Returns the rgb formatted color string
*/
var hash2rgb = function (hashColorStr) {
var str = '' + (hashColorStr || '');
var r, g, b;
str = str.replace(/^\s*#\s*/, '');
str = str.replace(/\s*$/, '');
if (str.length === 3) {
r = str.substr(0, 1);
g = str.substr(1, 1);
b = str.substr(2, 1);
r += r;
g += g;
b += b;
} else {
r = str.substr(0, 2);
g = str.substr(2, 2);
b = str.substr(4, 2);
}
r = parseInt(r, 16) || 0;
g = parseInt(g, 16) || 0;
b = parseInt(b, 16) || 0;
return 'rgb(' + r + ', ' + g + ', ' + b + ')';
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment