I want to convert given hex color to 3 digits if it's possible. For example:
#ffffff - #fff
#001122 - #012
#012345 - #012345
Does anyone know how to do it?
I found this regex in the google webs but I don't know how to use them :/
# shorten your CSS
sed -re 's/#(([0-9a-fA-F])\2)(([0-9a-fA-F])\4)(([0-9a-fA-F])\6)/#\2\4\6/'
# expand: the three-digit RGB notation (#rgb) is converted into six-digit form (#rrggbb) by replicating digits
sed -re 's/#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])\b/#\1\1\2\2\3\3/'
# works in egrep too
grep -E '(([0-9a-fA-F])\2)(([0-9a-fA-F])\4)(([0-9a-fA-F])\6)'
I want to convert given hex color to 3 digits if it's possible. For example:
#ffffff - #fff
#001122 - #012
#012345 - #012345
Does anyone know how to do it?
I found this regex in the google webs but I don't know how to use them :/
# shorten your CSS
sed -re 's/#(([0-9a-fA-F])\2)(([0-9a-fA-F])\4)(([0-9a-fA-F])\6)/#\2\4\6/'
# expand: the three-digit RGB notation (#rgb) is converted into six-digit form (#rrggbb) by replicating digits
sed -re 's/#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])\b/#\1\1\2\2\3\3/'
# works in egrep too
grep -E '(([0-9a-fA-F])\2)(([0-9a-fA-F])\4)(([0-9a-fA-F])\6)'
Share
Improve this question
asked Aug 29, 2015 at 21:43
katiekatie
1,0512 gold badges12 silver badges19 bronze badges
1
-
Simply do concatenation, var color = '#001122'; output =
${color[1] + color[3] + color[5]}
;-) – Naren Commented Feb 1, 2020 at 20:43
2 Answers
Reset to default 5There's probably a shorter and sweeter way, but you could perform simple char-parisons between the characters of the hex-color and if necessary manually assemble the string, for example:
var hex = "#aabb00";
if ((hex.charAt(1) == hex.charAt(2))
&& (hex.charAt(3) == hex.charAt(4))
&& (hex.charAt(5) == hex.charAt(6))) {
hex = "#" + hex.charAt(1) + hex.charAt(3) + hex.charAt(5);
}
May be below code will help you:
function hexToRgb(hex) {
// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
hex = hex.replace(shorthandRegex, function(m, r, g, b) {
return r + r + g + g + b + b;
});
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
function rgbToShortHex(rgb){
var hexR = Math.round(rgb.r / 17).toString(16);
var hexG = Math.round(rgb.g / 17).toString(16);
var hexB = Math.round(rgb.b / 17).toString(16);
return "#"+hexR+""+hexG+""+hexB;
}
function getShortHexColorCode(code){
var rgb = hexToRgb(code);
return rgbToShortHex(rgb);
}
alert(getShortHexColorCode("#ffffff"));
Check fiddle link
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745246158a4618420.html
评论列表(0条)