在JavaScript中将字符转换为ASCII代码

如何使用JavaScript将字符转换为其ASCII代码?

例如:

从“\n”中得到10。

1246580 次浏览
"\n".charCodeAt(0);

#0可以将字符串字符转换为ASCII数字。例如:

"ABC".charCodeAt(0) // returns 65

相反使用#0将数字转换为相等的ASCII字符。此函数可以接受多个数字并连接所有字符,然后返回字符串。示例:

String.fromCharCode(65,66,67); // returns 'ABC'

这是一个快速的ASCII字符参考:

{"31": "",      "32": " ",     "33": "!",     "34": "\"",    "35": "#","36": "$",     "37": "%",     "38": "&",     "39": "'",     "40": "(","41": ")",     "42": "*",     "43": "+",     "44": ",",     "45": "-","46": ".",     "47": "/",     "48": "0",     "49": "1",     "50": "2","51": "3",     "52": "4",     "53": "5",     "54": "6",     "55": "7","56": "8",     "57": "9",     "58": ":",     "59": ";",     "60": "<","61": "=",     "62": ">",     "63": "?",     "64": "@",     "65": "A","66": "B",     "67": "C",     "68": "D",     "69": "E",     "70": "F","71": "G",     "72": "H",     "73": "I",     "74": "J",     "75": "K","76": "L",     "77": "M",     "78": "N",     "79": "O",     "80": "P","81": "Q",     "82": "R",     "83": "S",     "84": "T",     "85": "U","86": "V",     "87": "W",     "88": "X",     "89": "Y",     "90": "Z","91": "[",     "92": "\\",    "93": "]",     "94": "^",     "95": "_","96": "`",     "97": "a",     "98": "b",     "99": "c",     "100": "d","101": "e",    "102": "f",    "103": "g",    "104": "h",    "105": "i","106": "j",    "107": "k",    "108": "l",    "109": "m",    "110": "n","111": "o",    "112": "p",    "113": "q",    "114": "r",    "115": "s","116": "t",    "117": "u",    "118": "v",    "119": "w",    "120": "x","121": "y",    "122": "z",    "123": "{",    "124": "|",    "125": "}","126": "~",    "127": ""}

如果你只有一个char而不是字符串,你可以使用:

'\n'.charCodeAt();'\n'.codePointAt();

省略0…

它曾经比'n'.charCodeAt(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);

对于那些想要获取字符串的所有ASCII代码总和的人:

'Foobar'.split('').map(char => char.charCodeAt(0)).reduce((current, previous) => previous + current)

或者,ES6:

[...'Foobar'].map(char => char.charCodeAt(0)).reduce((current, previous) => previous + current)

为了支持ES6中的所有UTF-16(也是非BMP/补充字符),可以使用string.codePointAt()方法;

此方法是charCodeAt的改进版本,仅支持Unicode代码点<65536(216-单个16位)。

JavaScript将字符串存储为UTF-16(双字节),因此如果您想忽略第二个字节,只需在0000000011111111(即255)上使用按位&运算符将其删除:

'a'.charCodeAt(0) & 255 === 97; // because 'a' = 97 0'b'.charCodeAt(0) & 255 === 98; // because 'b' = 98 0'✓'.charCodeAt(0) & 255 === 19; // because '✓' = 19 39

您可以输入一个字符并使用此代码获取Ascii代码

例如输入一个像A这样的字符你得到了Ascii代码65

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>

为确保完整的Unicode支持和可逆性,请考虑使用:

'\n'.codePointAt(0);

这将确保在测试超过UTF-16限制的字符时,您将获得它们的真实代码点值。

e. g.

'𐩕'.codePointAt(0); // 68181String.fromCodePoint(68181); // '𐩕'
'𐩕'.charCodeAt(0);  // 55298String.fromCharCode(55298);  // '�'
str.charCodeAt(index)

使用charCodeAt()以下示例返回65,即A的Unicode值。

'ABC'.charCodeAt(0)//返回65

要将String转换为累积数字:

const stringToSum = str => [...str||"A"].reduce((a, x) => a += x.codePointAt(0), 0);
console.log(stringToSum("A"));              // 65console.log(stringToSum("Roko"));           // 411console.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: 0console.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;}

将字符串转换为UTF-8的数组(流):

const str_to_arr_of_UTF8 = new TextEncoder().encode("Adfgdfs");// [65, 100, 102, 103, 100, 102, 115]

说明:ASCII是UTF-8的子集,所以这是一个通用的解决方案

对于那些想要获得具有平均值的字符串的所有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!'))

如果您仅使用128个原始ASCII字符(代码0到127),扩展阿尔瓦罗·冈萨雷斯和其他注释,字符码代码点非常好。在此范围之外,代码依赖于字符集,如果您希望结果有意义,则需要在计算之前进行字符集转换。

让我们以欧元符号为例:'€'.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);

charCodeAt(0);

Above code works in most cases, however there is a catch when working with words to find a ranking based on above code. For example, aa would give a ranking of 97+97 = 194 (actual would be 1+1 = 2) whereas w would give 119 (actual would be 23) which makes aa > w.To fix this subtract 96 from above result, to start he positioning from 1.

charCodeAt(0) - 96;

正如其他人所指出的,ASCII只包含128个字符(包括非打印字符)。Unicode出于向后兼容的目的,将ASCII作为其前128个字符,但它还包含更多的字符。

要获取只有 ASCII字符代码作为整数,您可以执行以下操作:

function ascii_code (character) {  
// Get the decimal codelet 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字符(例如,延迟字符串),您可以这样做:

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

来源