12

How do I convert, for example, the string "C3" to its character using JavaScript? I've tried charCodeAt, toString(16) and everything, but it doesn't work.

var justtesting = "C3"; // There's an input here
var tohexformat = '\x' + justtesting; // Gives the wrong hexadecimal number

var finalstring = tohexformat.toString(16);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
i.Dio
  • 177
  • 1
  • 2
  • 16

2 Answers2

22

All you need is parseInt and possibly String.fromCharCode.

parseInt accepts a string and a radix, a.k.a the base you wish to convert from.

console.log(parseInt('F', 16));

String.fromCharCode will take a character code and convert it to the matching string.

console.log(String.fromCharCode(65));

So here's how you can convert C3 into a number and, optionally, into a character.

var input = 'C3';
var decimalValue = parseInt(input, 16); // Base 16 or hexadecimal
var character = String.fromCharCode(decimalValue);
console.log('Input:', input);
console.log('Decimal value:', decimalValue);
console.log('Character representation:', character);
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
0

Another simple way is to print "&#" + CharCode like this:

for(var i=9984; i<=10175; i++){
    document.write(i + "&nbsp;&nbsp;&nbsp;" + i.toString(16) + "&nbsp;&nbsp;&nbsp;&#" + i + "<br>");
}

OR

for(var i=0x2700; i<=0x27BF; i++){
    document.write(i + "&nbsp;&nbsp;&nbsp;" + i.toString(16) + "&nbsp;&nbsp;&nbsp;&#" + i + "<br>");
}

JSFIDDLE

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Cody Tookode
  • 862
  • 12
  • 22