-3

How can I take a string like

John, Smith~2C John, Jones~2CMike

And replace these hex values indicated by ~ with their ASCII counterparts?

  • A hint: [How to convert from Hex to ASCII in JavaScript?](http://stackoverflow.com/questions/3745666/how-to-convert-from-hex-to-ascii-in-javascript). – Wiktor Stribiżew Sep 24 '15 at 22:03
  • 1
    I`ve been using the functions above, but how can I efficiently go through a string without constantly cutting the hex part out and replacing it in? – HeyThereBilly Sep 24 '15 at 22:14

1 Answers1

2

Assuming you always have 2 char hex-codes preceded by char ~, then /~[0-9A-F]{2}/i will give a match.
Now if we match globally and attach a function to replace, we can parse the integer using radix/base 16 and generate a character (using Object String's method fromCharCode) from that. Just don't forget to strip the trailing ~ character first.

Here is a short example to get you started:

function demo(s){
  return s.replace(/~[0-9A-F]{2}/gi, function(m){
    return String.fromCharCode(parseInt(m.slice(1), 16));
  });
}

console.log( demo('John, Smith~2C John, Jones~2CMike')  );

Hope this helps!

GitaarLAB
  • 14,536
  • 11
  • 60
  • 80