How to convert from Hex to ASCII in JavaScript?

Solution 1:

function hex2a(hexx) {
    var hex = hexx.toString();//force conversion
    var str = '';
    for (var i = 0; i < hex.length; i += 2)
        str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
    return str;
}
hex2a('32343630'); // returns '2460'

Solution 2:

Another way to do it (if you use Node.js):

var input  = '32343630';
const output = Buffer.from(input, 'hex');
log(input + " -> " + output);  // Result: 32343630 -> 2460

Solution 3:

For completeness sake the reverse function:

function a2hex(str) {
  var arr = [];
  for (var i = 0, l = str.length; i < l; i ++) {
    var hex = Number(str.charCodeAt(i)).toString(16);
    arr.push(hex);
  }
  return arr.join('');
}
a2hex('2460'); //returns 32343630

Solution 4:

You can use this..

var asciiVal = "32343630".match(/.{1,2}/g).map(function(v){
      return String.fromCharCode(parseInt(v, 16));
    }).join('');
    
document.write(asciiVal);

Solution 5:

I found a useful function present in web3 library.

var hexString = "0x1231ac"
string strValue = web3.toAscii(hexString)

Update: Newer version of web3 has this function in utils

The functions now resides in utils:

var hexString = "0x1231ac"
string strValue = web3.utils.hexToAscii(hexString)