Javascript-converting full-width and half-width characters-javascript tips-js tutorial

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.