What is an easy way to call Asc() and Chr() in JavaScript for Unicode values?
I am not that familiar with Javascript, and am looking for the function that returns the UNICODE value of a character, and given the UNICODE value, returns the string equivalent. I'm sure there is something simple, but I don't see it.
Example:
- ASC("A") = 65
- CHR(65) = "A"
- ASC("ਔ") = 2580
- CHR(2580) = "ਔ"
Have a look at:
String.fromCharCode(64)
and
String.charCodeAt(0)
The first must be called on the String class (literally String.fromCharCode...
) and will return "@" (for 64). The second should be run on a String instance (e.g., "@@@".charCodeAt...
) and returns the Unicode code of the first character (the '0' is a position within the string, you can get the codes for other characters in the string by changing that to another number).
The script snippet:
document.write("Unicode for character ਔ is: " + "ਔ".charCodeAt(0) + "<br />");
document.write("Character 2580 is " + String.fromCharCode(2580) + "<br />");
gives:
Unicode for character ਔ is: 2580 Character 2580 is ਔ
Because JavaScript uses UCS-2 internally, String.fromCharCode(codePoint)
won’t work for supplementary Unicode characters. If codePoint
is 119558
(0x1D306
, for the '𝌆'
character), for example.
If you want to create a string based on a non-BMP Unicode code point, you could use Punycode.js’s utility functions to convert between UCS-2 strings and UTF-16 code points:
// `String.fromCharCode` replacement that doesn’t make you enter the surrogate halves separately
punycode.ucs2.encode([0x1d306]); // '𝌆'
punycode.ucs2.encode([119558]); // '𝌆'
punycode.ucs2.encode([97, 98, 99]); // 'abc'
if you want to get the Unicode code point for every character in a string, you’ll need to convert the UCS-2 string into an array of UTF-16 code points (where each surrogate pair forms a single code point). You could use Punycode.js’s utility functions for this:
punycode.ucs2.decode('abc'); // [97, 98, 99]
punycode.ucs2.decode('𝌆'); // [119558]
Example for generating alphabet array here :
const arr = [];
for(var i = 0; i< 20; i++) {
arr.push( String.fromCharCode('A'.charCodeAt(0) + i) )
}