---
title: "全角与半角转换"
author: "ianylb"
date: "2012-08-14T21:34:42Z"
tags: []
categories: ["Web前端"]
slug: "untitled"
draft: false
lastmod: "2012-08-16T20:36:36Z"
id: 1632058
url: "https://yelb.iteye.com/blog/1632058"
---

试着用jquery插件的方式将全角与半角的函数写成插件。

 

///全角空格为12288，半角空格为32 

///其他半角字符半角(33-126)与全角(65281-65374)的对应关系是：均相差65248 

(function($){

$.extend({

//全角转换为半角函数

toCdb : function(str){

var result="";

var charCode;

for (var i = 0; i &lt; str.length; i++) {

charCode = str.charCodeAt(i);

//转换空格

if (charCode==12288) {

result+= String.fromCharCode(charCode-12256);

continue;

}

if (charCode &gt; 65280 && charCode &lt;65375)

result+= String.fromCharCode(charCode - 65248);

else result+= String.fromCharCode(charCode);

} 

 

return result;

},

 

//半角转换为全角函数

toDbc: function(str){

var tmp = "";

var charCode; 

for(var i=0;i&lt;str.length;i++) {  

charCode = str.charCodeAt(i);

if(charCode == 32) { 

tmp= tmp+  String.fromCharCode(12288);

}

 

if(charCode &gt; 33 && charCode &lt; 127) {

tmp=tmp+String.fromCharCode(charCode + 65248);

} else {

tmp=tmp+String.fromCharCode(charCode);

}

}

 

return tmp;     

}

});

}(jQuery))