JavaScript 如何将字符转换为ASCII码
本文的目的是通过使用JavaScript获取任意字符的ASCII码 charCodeAt() 方法。该方法用于返回指定索引处字符的Unicode值。
语法:
string.charCodeAt(index);
示例: 下面的代码说明了它们可以从用户输入一个字符,并显示该字符的ASCII码。
<body style="text-align:center;">
<h2 style="color:green">
GeeksForGeeks
</h2>
<h2>
How to convert character to
ASCII code in JavaScript
</h2>
<p>
Enter any character:
<input type="text" id="id1" name="text1" maxLength="1">
</p>
<button onclick="myFunction()">
Get ASCII code
</button>
<p id="demo" style="color:red;">
</body>
Javascript代码
function myFunction() {
var str = document.getElementById("id1");
if (str.value == "") {
str.focus();
return;
}
var a = "ASCII Code is == > ";
document.getElementById("demo").innerHTML
= a + str.value.charCodeAt(0);
}
输出: