Help with creating a buffer of hex bytes from a string of hex words

I knew you'd crack this a lot faster. Meanwhile I was only able to cobble together this inferior version:

let str = msg.payload.split(' ').join('');
msg.payload = hexStringToBuffer(str);

return msg;

function hexStringToBuffer(str) {
  let a = [];
  for (let i = 0, len = str.length; i < len; i += 2) {
    a.push(parseInt(str.substr(i,2), 16));
  }
  
  return Buffer.from(a);
}

Great to learn there's even a simpler version. But what boggled me the most is why str.replaceAll(' ', ''); gave me an unknown function error. I'm running Node 14 and I'm pretty sure I've used the syntax multiple times earlier on. With that said, my JS seems to be getting rusty after a 6 month of break writing it at work...

2 Likes