Home > Article > Web Front-end > Conversion between characters and character encodings
1.charCodeAt() and charAt() methods.
Strings and character encodings can be converted to each other. If you want to convert a string to a character encoding, you can choose to use the charCodeAt() method, as follows:
Java code
var str="NO do,no die,why you try"; var theTencharcode=str.charCodeAt(0); console.log(theTencharcode);//结果为100;
Where, string is a string, The parentheses of the charCodeAt() method is the index of the character expected to be converted. We need to take the code of its 10th character 'd'. Its index value starts from 0, so the index value is 9. Finally, the printed result 100 is what we want The encoding of the converted character;
If you just want to select characters, you can use the charAt() method. The charAt() method is similar to charCodeAt(). Also use the above example:
Java code
var str="NO do,no die,why you try"; var theTencharcode=str.charAt(9) console.log(theTencharcode);结果为'd';
The output result is us The character you are looking for is 'd';
2. fromCharCode() method
is just the opposite of the charCodeAt() method. Send it a set of comma-separated numbers representing character encodings, and this method will convert them to a string. For example, save the string 'love' in the variable myHeart:
Java code
var myHeart; myHeart=String.fromCharCode(108,111,118,101); console.log(myHeart);
The fromCharCode() method alone has no use. It is more suitable to use it with a variable, such as to output a message containing Strings of all lowercase letters in the alphabet:
Java code
var base_char=''; for(var charCode=97;charCode<=122; charCode++) { base_char +=String.fromCharCode(charCode); } console.log(base_char);
In addition, I personally think that the above method is suitable for encryption and decryption.