I want to convert a 3-digit hex color which is coming from HTML CSS to a 6-digit hex color for Flex. Can anyone give me code to convert 3-digit hex colors to their 6-digit equivalents?
Asked
Active
Viewed 2.2k times
34
-
1Possible duplicate of [convert to 3-digit hex color code](http://stackoverflow.com/questions/1459273/convert-to-3-digit-hex-color-code) – Massimiliano Kraus Jan 04 '17 at 13:16
6 Answers
11
Double every digit: for example #A21
is equal to #AA2211
.
However this question is a duplicate of: convert to 3-digit hex color code
9
Other answers provided the process but I will provide the code using regex and the java programming language
String value = "#FFF";
value = value.replaceAll("#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])", "#$1$1$2$2$3$3");

Ovokerie Ogbeta
- 503
- 7
- 5
1
If you came here and is using Python, here's how:
hex_code = '#FFF'
new_hex_code = '#{}'.format(''.join(2 * c for c in hex_code.lstrip('#')))

bertdida
- 4,988
- 2
- 16
- 22
1
Kotlin version of Ovokerie's answer:
shortHexString.replace(Regex("#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])"), "#$1$1$2$2$3$3")

Peter Keefe
- 1,095
- 14
- 22
1
PHP Version:
/**
* returns a clean 6 digit hex number as a string
* @param $hex
* @return false|string
*/
function clean_hex_color($hex)
{
$hex = strtolower($hex);
//remove the leading "#"
if (strlen($hex) == 7 || strlen($hex) == 4)
$hex = substr($hex, -(strlen($hex) - 1));
// $hex like "1a7"
if (preg_match('/^[a-f0-9]{6}$/i', $hex))
return $hex;
// $hex like "162a7b"
elseif (preg_match('/^[a-f0-9]{3}$/i', $hex))
return $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
//any other format
else
return "000000";
}

Gogo
- 292
- 8
- 19