How to convert a hexadecimal string to Uint8Array and back in JavaScript?

Node.js

For JavaScript running on Node you can do this:

const hexString = 'bada55';

const hex = Uint8Array.from(Buffer.from(hexString, 'hex'));

const backToHexString = Buffer.from(hex).toString('hex');

(source: this answer by @Teneff, shared with permission)


Vanilla JS:

const fromHexString = (hexString) =>
  Uint8Array.from(hexString.match(/.{1,2}/g).map((byte) => parseInt(byte, 16)));

const toHexString = (bytes) =>
  bytes.reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), '');

console.log(toHexString(Uint8Array.from([0, 1, 2, 42, 100, 101, 102, 255])));
console.log(fromHexString('0001022a646566ff'));

Note: this method trusts its input. If the provided input has a length of 0, an error will be thrown. If the length of the hex-encoded buffer is not divisible by 2, the final byte will be parsed as if it were prepended with a 0 (e.g. aaa is interpreted as aa0a).

If the hex is potentially malformed or empty (e.g. user input), check its length and handle the error before calling this method, e.g.:

const isHex = (maybeHex) =>
  maybeHex.length !== 0 && maybeHex.length % 2 === 0 && !/[^a-fA-F0-9]/u.test(maybeHex);

const missingLetter = 'abc';

if (!isHex(missingLetter)) {
  console.log(`The string "${missingLetter}" is not valid hex.`)
} else {
  fromHexString(missingLetter);
}

Source: the Libauth library (hexToBin method)