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);
6
  • "stackoverflow.com/questions/26301638/…" related!! Commented Dec 5, 2016 at 14:52
  • You also don't have quotes around C3, so it's not interpreting it as a string. Commented Dec 5, 2016 at 14:53
  • yes i do. edited :) Commented Dec 5, 2016 at 14:54
  • OP is not attempting to convert decimal values to hexadecimal. Commented Dec 5, 2016 at 14:55
  • yep. it's a string.. i just can't turn a string to an hex, i.e 31 to number 1 cause when i try to add \x it gives me just two more chars, instead of a hex value Commented Dec 5, 2016 at 14:56

2 Answers 2

23

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);

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

Is this a bogus answer? What are the magic numbers 9984 and 10175? What is the intent?
@PeterMortensen magic numbers are just a decimal representation of utf-8 character. The intent to demostrate a simple example how to turn a hexadecimal/decimal number into a char using javascript.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.