A codegolfed approach:
var h = x => '#' + x.match(/\d+/g).map(y = z => ((+z < 16)?'0':'') + (+z).toString(16)).join('');
Now, running h("rgb(255, 60, 60)")
will return #ff3c3c
.
You can replace '#'
with '0x'
to get outputs in the form of 0xff3c3c
.
EXTRA: how it works.
h
, declared as an arrow function (new in ES6) takes an RGB value (string) and stores it in x
.
Then, all instances of numbers in x
are found by the regex equation /\d+/g
, and used further as an array (returned by match
, used by map
).
map
loops processes all the elements of the returned array by a function y
.
The function takes a value (which was stored in the array as a string) as z
converts it to a number (+z
), checks if it is less than 16 (((+z < 16)?'0':'')
, that is, the hex representation has a single digit), and if true, adds a '0'
to the element's start.
Then, it converts it to a string of base 16 (hex, by .toString(16)
), and returns it to map
. So essentially, all the decimal strings in the array are now changed to hex strings.
Finally, the array's elements are joined together (join('')
), with no delimiter and '#'
is added to the beginning of the string.
Note: If the code is supplied a value greater than 255, the output will be more than 6 hex digits. Like, the output for rgb(256, 0, 0)
will be #1000000
.
To constraint the value to 255, this would be the code:
var h = x => '#' + x.match(/\d+/g).map(y = z => ((+z < 16)?'0':'') + ((+z > 255)?255:+z).toString(16)).join('');