如何使用JavaScript将字符转换为其ASCII码?
例如:
从“\n”获取10。
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);
}
<p>Check ASCII code</p>
<p>
Enter any character:
<input type="text" id="id1" name="text1" maxLength="1"> </br>
</p>
<button onclick="myFunction()">Get ASCII code</button>
<p id="demo" style="color:red;"></p>
为了支持ES6中所有UTF-16字符(包括非BMP/补充字符),可以使用 string.codePointAt() 方法;
这个方法是charCodeAt的改进版本,charCodeAt只能支持Unicode码点< 65536(216-一个16位数)。
String.prototype.codePointAt()
方法在任何版本的Internet Explorer中均不受支持(但在Edge上受支持)。您可以在此处获得一个polyfill。 - mgthomas99str.charCodeAt(index)
使用charCodeAt()
A
的Unicode值。
'ABC'.charCodeAt(0)
// 返回65
扩展 Álvaro González 和其他人的评论,如果您仅使用128个原始ASCII字符(代码0到127),则charCodeAt或codePointAt非常好用。超出此范围代码取决于字符集,如果要计算结果使其有意义,则需要进行字符集转换。
以欧元符号为例:'€'.codePointAt(0)
返回8364
,远超出0-127范围,并且与UTF-16(或UTF-8)字符集相关。
Asc
函数获取字符代码。显然,从它的角度来看,它会返回Windows-1252字符集中的字符代码。为了确保获得相同的数字,我需要转换字符串字符集,然后计算代码。ord('€'.encode('Windows-1252'))
。
然而,在Javascript中实现相同的功能,我不得不使用缓冲区和转换库:iconv = require('iconv-lite');
buf = iconv.encode("€", 'win1252');
buf.forEach(console.log);
let ascii_chars = "";
for (let i = 32; i <= 126; ++i) {
ascii_chars += String.fromCharCode(i);
}
document.write(ascii_chars);
charCodeAt(0);
charCodeAt(0) - 96;
对于那些想要获取一个字符串中所有ASCII码的总和并计算平均值的人:
const ASCIIAverage = (str) =>Math.floor(str.split('').map(item => item.charCodeAt(0)).reduce((prev,next) => prev+next)/str.length)
console.log(ASCIIAverage('Hello World!'))
function ascii_code (character) {
// Get the decimal code
let code = character.charCodeAt(0);
// If the code is 0-127 (which are the ASCII codes,
if (code < 128) {
// Return the code obtained.
return code;
// If the code is 128 or greater (which are expanded Unicode characters),
}else{
// Return -1 so the user knows this isn't an ASCII character.
return -1;
};
};
function ascii_out (str) {
// Takes a string and removes non-ASCII characters.
// For each character in the string,
for (let i=0; i < str.length; i++) {
// If the character is outside the first 128 characters (which are the ASCII
// characters),
if (str.charCodeAt(i) > 127) {
// Remove this character and all others like it.
str = str.replace(new RegExp(str[i],"g"),'');
// Decrement the index, since you just removed the character you were on.
i--;
};
};
return str
};
€
,获取128
? - simlev€
符号,因为它是在货币符号出现几十年前创建的。在Windows-1252编码中,128
代表了这个符号。但是,在随意转换编码时会遇到问题。请注意保持原意。 - Álvaro González