[英]Convert character to ASCII code in JavaScript
如何使用 JavaScript 將字符轉換為其 ASCII 碼?
例如:
從“\n”中得到 10。
"\n".charCodeAt(0);
String.prototype.charCodeAt()
可以將字符串字符轉換為 ASCII 數字。 例如:
"ABC".charCodeAt(0) // returns 65
相反,使用String.fromCharCode(10)
將數字轉換為相等的 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": ""
}
如果您只有一個字符而不是字符串,則可以使用:
'\n'.charCodeAt();
省略 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(x=>x.charCodeAt(0))
.reduce((a,b)=>a+b);
或者,ES6:
[...'Foobar']
.map(char => char.charCodeAt(0))
.reduce((current, previous) => previous + current)
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
為確保完全 Unicode 支持和可逆性,請考慮使用:
'\n'.codePointAt(0);
這將確保在測試超過 UTF-16 限制的字符時,您將獲得它們的真實代碼點值。
例如
'𐩕'.codePointAt(0); // 68181
String.fromCodePoint(68181); // '𐩕'
'𐩕'.charCodeAt(0); // 55298
String.fromCharCode(55298); // '�'
您可以輸入一個字符並使用此代碼獲取 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>
要將字符串轉換為累積數字:
const stringToSum = str => [...str||"A"].reduce((a, x) => a += 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; }
為了支持 ES6 中的所有 UTF-16(也是非 BMP/補充字符),可以使用string.codePointAt()方法;
此方法是 charCodeAt 的改進版本,它只能支持小於 65536(2 16 - 單個 16 位)的 unicode 代碼點。
str.charCodeAt(index)
使用charCodeAt()
以下示例返回 65,即A
的 Unicode 值。
'ABC'.charCodeAt(0)
// 返回 65
可以使用for循環獲取所有可打印ASCII字符的列表。
for(var i = 33; i < 127; i++){ document.write("<p>"+i + ": " + String.fromCharCode(i)+"</p>"); }
將字符串轉換為 UTF-8 的數組(流):
const str_to_arr_of_UTF8 = new TextEncoder().encode("Adfgdfs");
結果 - [65, 100, 102, 103, 100, 102, 115]
對於那些想要獲得具有平均值的字符串的所有 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!'))
擴展Álvaro González和其他人的評論,如果您僅使用 128 個原始 ASCII 字符(代碼 0 到 127),則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);
charCodeAt(0);
上面的代碼在大多數情況下都有效,但是在使用單詞查找基於上面的代碼的排名時有一個問題。 例如,aa 將給出 97+97 = 194(實際將是 1+1 = 2)的排名,而 w 將給出 119(實際將是 23),這使得 aa > w。 要從上面的結果中減去 96,從 1 開始定位。
charCodeAt(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 字符(例如,對字符串進行 slugifying),您可以執行以下操作:
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
};
也許這也很有用(按 ascii 表中的順序排列的 ascii 字符):
let ascii_chars = "";
for (let i = 32; i <= 126; ++i) {
ascii_chars += String.fromCharCode(i);
}
document.write(ascii_chars);
使用方法charCodeAt
console.log("\n".charCodeAt())
使用方法fromCharCode
console.log(String.fromCharCode(10))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.