Home  >  Article  >  Web Front-end  >  Conversion between characters and character encodings

Conversion between characters and character encodings

巴扎黑
巴扎黑Original
2016-11-25 13:55:411408browse

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:

var str="NO do,no die,why you try";  
var theTencharcode=str.charCodeAt(0);  
console.log(theTencharcode);//结果为100;

​ Among them, string is a string, charCodeAt( ) method is the index of the character that is expected to be converted. We need to take the encoding of its 10th character 'd'. Its index value starts from 0, so the index value is 9. Finally, the printed result 100 is what is to be converted. Character encoding;

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:

var str="NO do,no die,why you try";  
var theTencharcode=str.charAt(9)  
console.log(theTencharcode);结果为'd';

The output result is the character we are looking for. '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 into a string. For example, save the string 'love' in the variable myHeart:

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 letter containing all letters. The string of lowercase letters in the table:

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.


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn