Home  >  Article  >  Web Front-end  >  Javascript realizes the conversion of full-width and half-width characters_javascript skills

Javascript realizes the conversion of full-width and half-width characters_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:21:511252browse

First code, then talk nonsense^_^

Copy code The code is as follows:

/**
* Convert full-width characters
​*/
function toDBC(str){
var result = "";
var len = str.length;
for(var i=0;i {
      var cCode = str.charCodeAt(i);
//The difference between full-width and half-width (except spaces): 65248 (decimal)
cCode = (cCode>=0x0021 && cCode<=0x007E)?(cCode 65248) : cCode;
​​​​ //Handle spaces
cCode = (cCode==0x0020)?0x03000:cCode;
         result = String.fromCharCode(cCode);
}
Return result;
}
/**
* Convert half-width characters
​*/
function toSBC(str){
var result = "";
var len = str.length;
for(var i=0;i {
      var cCode = str.charCodeAt(i);
//The difference between full-width and half-width (except spaces): 65248 (decimal)
cCode = (cCode>=0xFF01 && cCode<=0xFF5E)?(cCode - 65248) : cCode;
​​​​ //Handle spaces
cCode = (cCode==0x03000)?0x0020:cCode;
         result = String.fromCharCode(cCode);
}
Return result;
}

Knowledge Points

By comparing half-width characters and full-width characters (ASCII characters), we can find that there are full-width and half-width ASCII character ranges: 0x20~0x7E.

For example:

Symbols half-width and full-width differ
# 0x0023 0xFF03 0xFEE0
? 0x003F 0xFF1F 0xFEE0
Space 0x0020 0x03000 0x2FE0

Except for spaces, the difference between full-width and half-width characters is: 0xFFE0

Therefore, when converting full-width and half-width characters, special treatment of spaces is required.

For example:

Full-width = half-width 0xFEE0

Half-width = full-width - 0xFFE0

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