This article mainly introduces the code and knowledge points for converting full-width and half-width characters in javascript. If you need it, refer to the code first.
The Code is as follows:
/**
* Convert to fullwidth characters
*/
Function toDBC (str ){
Var result = "";
Var len = str. length;
For (var I = 0; I {
Var cCode = str. charCodeAt (I );
// Difference between the fullwidth and halfwidth (except space): 65248 (decimal)
CCode = (cCode> = 0x0021 & cCode <= 0x007E )? (CCode + 65248): cCode;
// Process Spaces
CCode = (cCode = 0x0020 )? 0x03000: cCode;
Result + = String. fromCharCode (cCode );
}
Return result;
}
/**
* Halfwidth characters
*/
Function toSBC (str ){
Var result = "";
Var len = str. length;
For (var I = 0; I {
Var cCode = str. charCodeAt (I );
// Difference between the fullwidth and halfwidth (except space): 65248 (decimal)
CCode = (cCode >=0xff01 & cCode <= 0xFF5E )? (CCode-65248): cCode;
// Process Spaces
CCode = (cCode = 0x03000 )? 0x0020: cCode;
Result + = String. fromCharCode (cCode );
}
Return result;
}
Knowledge Point
By comparing the halfwidth characters with the fullwidth characters (ASCII characters), we can find that the range of ASCII characters is 0x20 ~ 0x7E.
For example:
Symbol halfwidth difference
#0x0023 0xFF03 0xFEE0
? 0x003F 0xFF1F 0xFEE0
Space 0x0020 0x03000 0x2FE0
Except for spaces, the difference between the full and half-width characters is 0xFFE0.
Therefore, spaces must be specially processed in character conversion between the full and half-width fields.
For example:
Fullwidth = halfwidth + 0xFEE0
Halfwidth = fullwidth-0xFFE0