如何使用 JavaScript 将字符串
"C3"
转换为其字符?我已经尝试过charCodeAt
,toString(16)
等等,但它不起作用。
var justtesting = "C3"; // There's an input here
var tohexformat = '\x' + justtesting; // Gives the wrong hexadecimal number
var finalstring = tohexformat.toString(16);
parseInt
,可能还有 String.fromCharCode
。
parseInt
接受一个字符串和一个 radix,也就是你想要转换的基数。
console.log(parseInt('F', 16));
String.fromCharCode
将获取字符代码并将其转换为匹配的字符串。
console.log(String.fromCharCode(65));
以下是如何将
C3
转换为数字,也可以选择转换为字符。
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);
另一种简单的方法是像这样打印“&#”+ CharCode
for(var i=9984;i<=10175;i++){
document.write(i+ " " + i.toString(16) + " &#" + i +"<br>");
}
或
for(var i=0x2700;i<=0x27BF;i++){
document.write(i+ " " + i.toString(16) + " &#" + i +"<br>");
}