当前位置:软件学堂 > 资讯首页 > 网络编程 > 编程其他 > JS实现全角转半角

JS实现全角转半角

2012/11/13 16:16:59作者:佚名来源:网络

移动端

【实例名称】

JS实现全角转半角

【实例描述】

全角是中文输入法下的一种字符形态。为了控件界面的字符效果,本例提供一种全角转半角的方法。

【实例代码】

<html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>标题页-学无忧(www.xue51.com)</title> <script LANGUAGE="JavaScript"> function fullChar2halfChar(str) {  var result = '';  for (i=0 ; i<str.length; i++)  {   code = str.charCodeAt(i);             //获取当前字符的unicode编码   if (code >= 65281 && code <= 65373)   //unicode编码范围是所有的英文字母以及各种字符   {    result += String.fromCharCode(str.charCodeAt(i) - 65248);    //把全角字符的unicode编码转换为对应半角字符的unicode码   }   else if (code == 12288)                                      //空格   {    result += String.fromCharCode(str.charCodeAt(i) - 12288 + 32); //半角空格   }else   {    result += str.charAt(i);                                     //原字符返回   }  }  return result; } </script> </head> <body> 全角<input type=text name="txt1" value="this is !"><br /> 半角<input type=text name="txt2" value=""> <input type=button value="转换文本" onClick="txt2.value=fullChar2halfChar(txt1.value)"> </body> </html>

【运行效果】

 全角转半角运行效果

【难点剖析】

本例的难点是unicode编码。可使用字符串对象的“charCodeAt”方法获取某个字符的unicode编码,然后根据编码范围逐个检测用户输入的文本,如果编码范围在“65281~65373”之间,则表示当前字符是全角,用此值减去“65248”便是半角符号。

【源码下载】

为了JS代码的准确性,请点击:JS实现全角转半角 进行本实例源码下载 

标签: 转换