snippetjavascriptCritical
Convert character to ASCII code in JavaScript
Viewed 0 times
asciiconvertcharacterjavascriptcode
Problem
How can I convert a character to its ASCII code using JavaScript?
For example:
get 10 from "\n".
For example:
get 10 from "\n".
Solution
"\n".charCodeAt(0);Here is the documentation for
charCodeAt:The
charCodeAt() method returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index.The UTF-16 code unit matches the Unicode code point for code points which can be represented in a single UTF-16 code unit. If the Unicode code point cannot be represented in a single UTF-16 code unit (because its value is greater than
0xFFFF) then the code unit returned will be the first part of a surrogate pair for the code point. If you want the entire code point value, use codePointAt().If you need to support non-BMP Unicode characters like U+1F602 😂, then don't use
charCodeAt, as it will not return 128514 (or 0x1f602 in hexadecimal), it will give a result you don't expect:console.log("\u{1f602}".charCodeAt(0));
// prints 55357 , which is 0xd83d in hexadecimalCode Snippets
"\n".charCodeAt(0);Context
Stack Overflow Q#94037, score: 1834
Revisions (0)
No revisions yet.