如何使用JavaScript将字符转换为ASCII码?
例如:
从“\n”中得到10。
如何使用JavaScript将字符转换为ASCII码?
例如:
从“\n”中得到10。
当前回答
如果您只使用128个原始ASCII字符(代码0到127),那么扩展Álvaro González和其他注释,charCodeAt或codePointAt非常好。在此范围之外,代码依赖于字符集,如果希望结果有意义,则需要在计算之前进行字符集转换。
让我们以欧元符号为例:'€'. codepointat(0)返回8364,这远远超出了0-127的范围,并且相对于UTF-16(或UTF-8)字符集。
我移植了一个Visual Basic程序,并注意到它使用Asc函数来获取字符代码。显然,从它的角度来看,它将返回Windows-1252字符集中的字符代码。为了确保获得相同的数字,我需要转换字符串字符集,然后计算代码。
非常简单,例如在Python中:ord('€'.encode('Windows-1252'))。 然而,为了在Javascript中实现同样的效果,我不得不求助于缓冲区和转换库:
iconv = require('iconv-lite');
buf = iconv.encode("€", 'win1252');
buf.forEach(console.log);
其他回答
如果你只有一个字符而不是字符串,你可以使用:
'\n'.charCodeAt();
'\n'.codePointAt();
省略0…
它曾经比'n'. charcodeat(0)慢得多,但我现在已经测试过了,我再也看不到任何区别了(带0和不带0执行了100亿次)。仅在Chrome和Firefox中测试了性能。
虽然其他答案都是正确的,但我更喜欢这样:
function ascii (a) { return a.charCodeAt(0); }
然后,要使用它,简单地:
var lineBreak = ascii("\n");
我正在使用这个小快捷系统:
$(window).keypress(function(event) {
if (event.ctrlKey && event.which == ascii("s")) {
savecontent();
}
// ...
});
你甚至可以在map()或其他方法中使用它:
var ints = 'ergtrer'.split('').map(ascii);
charCodeAt(0);
以上代码在大多数情况下都可以工作,但是在使用单词查找基于上述代码的排名时存在一个问题。例如,aa会给出97+97 = 194(实际会是1+1 = 2),而w会给出119(实际会是23),这使得aa > w。 要解决这个问题,从上面的结果减去96,从1开始定位。
字符代码(0) - 96;
正如其他人指出的那样,ASCII只包含128个字符(包括非打印字符)。为了向后兼容,Unicode将ASCII作为其前128个字符,但它还包括更多字符。
如果只获取整数形式的ASCII字符码,您可以执行以下操作:
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;
};
};
如果你只寻找字符串中的ASCII字符(例如,slugified一个字符串),你可以这样做:
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
};
来源
https://www.geeksforgeeks.org/ascii-vs-unicode/: ~:文本Unicode % 20 = % 20 % 20普遍% 20字符,编码% 20标准% 20 % 20电子% 20的沟通。 https://www.w3schools.com/jsref/jsref_charcodeat.asp
将字符串转换为累积数:
const stringToSum = str => [...str||”A“].reduce((a, x) => and += x.codePointAt(0), 0); console.log(stringToSum(“A”)); 65 console.log(stringToSum(“Roko”)); 411 console.log(stringToSum(“Stack Overflow”));1386
用例:
假设你想根据用户名生成不同的背景颜色:
const stringToSum = str => [...str||"A"].reduce((a, x) => a += x.codePointAt(0), 0); const UI_userIcon = user => { const hue = (stringToSum(user.name) - 65) % 360; // "A" = hue: 0 console.log(`Hue: ${hue}`); return `<div class="UserIcon" style="background:hsl(${hue}, 80%, 60%)" title="${user.name}"> <span class="UserIcon-letter">${user.name[0].toUpperCase()}</span> </div>`; }; [ {name:"A"}, {name:"Amanda"}, {name:"amanda"}, {name:"Anna"}, ].forEach(user => { document.body.insertAdjacentHTML("beforeend", UI_userIcon(user)); }); .UserIcon { width: 4em; height: 4em; border-radius: 4em; display: inline-flex; justify-content: center; align-items: center; } .UserIcon-letter { font: 700 2em/0 sans-serif; color: #fff; }