Working with hex strings and hex values more easily in Javascript


No, there is no way to tell the JavaScript language to use hex integer format instead of decimal by default. Your code is about as concise as it gets but note that you do not need to prepend the "0x" base indicator when you use "parseInt" with a base.

Here is how I would approach your problem:

function addHexColor(c1, c2) {
  var hexStr = (parseInt(c1, 16) + parseInt(c2, 16)).toString(16);
  while (hexStr.length < 6) { hexStr = '0' + hexStr; } // Zero pad.
  return hexStr;

addHexColor('aaaaaa', '010101'); // => 'ababab'
addHexColor('010101', '010101'); // => '020202'

How about this:

var hexValue = "aaaaaa";
hexValue = (parseInt(hexValue, 16) + 0x010101).toString(16);
document.writeln(hexValue); // outputs 'ababab'

There is no need to add the 0x prefix if you use parseInt.

I think accepted answer is wrong. Hexadecimal color representation is not a linear. But instead, 3 sets of two characters are given to R, G & B.

So you can't just add a whole number and expect to RGB to add up correctly.

For Example

n1 = '005500'; <--- green
n2 = '00ff00'; <--- brighter green

Adding these numbers should result in a greener green. In no way, adding greens should increase RED to increase. but by doing what accepted answer is doing, as in just treat whole number as one number then you'd carry over for numbers adding upto greater than f, f+1 = 10.

you get `015400` so by adding greens the RED increased .... WRONG

adding 005500 + 00ff00 should result in, = 00ff00. You can't add more green to max green.