Original code:
Copy codeThe Code is as follows: // convert text to hexadecimal
Function textToSix (str ){
Return escape (str). replace (/%/g, function (){
Return "\\";
}). ToLowerCase ();
}
After improvement:Copy codeThe Code is as follows: // convert text to hexadecimal
Function textToHex (str ){
// Output % u *** format when encoding unicode values other than 0-, for example: % u6267 % u624b % u6cea % u773c
// Replace % with \, which is in hexadecimal format.
If (typeof str = "string "){
Return escape (str). replace (/%/g, function (){
Return "\\";
}). ToLowerCase ();
} Else {
Return null;
}
}
It mainly adds a token to verify whether it is a string.
After completing this method, I thought it was necessary to improve the following method:Copy codeThe Code is as follows: // The hexadecimal representation is text.
Function sixToText (str ){
Return unescape (str );
}
It is intended to convert characters such as "\ unnn" back to text. In fact, you only need to look at the principles of the unescape method (Working principle: Find the character sequence in the form of % xx and % uxxxx (x indicates the hexadecimal number ), use Unicode characters \ u00xx and \ uxxxx to replace such character sequences for decoding. From Baidu encyclopedia ). You will know that I do this all. Because the browser can parse hexadecimal characters. For example:
In IE9:
In Chrome:
Let's add another benefit. In fact, when I used this parsing to replace the replaced character, my initial thought was to replace "\" with "% ", then use the unescape decoding function to parse characters. However, when I want to replace "\" with "%", I find the following interesting phenomenon: if the character "\" is not followed by "t", "n" can be combined with t to form a conversion character, it will be ignored by the browser. Use experiments to verify my conclusions:
Debugging in IE9:
Debug in Chrome:
A variable is defined here, which contains some characters that may rarely appear at ordinary times "\". When debugging, check the above prompt, the browser intelligently ignores characters in special locations. Therefore, when you place seemingly common characters (such as file paths) in js variables, the output may not be as expected.