---
title: "JavaScript 全角字符转半角字符"
author: "bornlone"
date: "2009-01-09T23:21:01Z"
tags: []
categories: ["Web前端"]
slug: "javascript"
draft: false
lastmod: "2010-02-05T16:57:47Z"
id: 314002
url: "https://bornlone.iteye.com/blog/314002"
---

```
<html>
<head>
<script language="javascript">
   //方法描述：把指定输入框中的全角字符转为半角字符，并在输入框失去焦点时自动改变输入框中的全角字符
  //原理说明：
  //      1、全角空格为12288，半角空格为32
   //      2、其他字符半角(33-126)与全角(65281-65374)的对应关系是：均相差65248
        function FullToDBC(obj){
                var Str = obj.value;
                var DBCStr = "";
                for(var i = 0; i < Str.length; i++){
                        var c = Str.charCodeAt(i);
                        if(c == 12288){
                                DBCStr += String.fromCharCode(32);
                                continue;
                        }
                        if(c > 65280 && c < 65375){
                                DBCStr += String.fromCharCode(c - 65248);
                                continue;
                        }
                        DBCStr += String.fromCharCode(c);
                }
                obj.value = DBCStr;
        }
</script>
</head>

<body>
<center>
        <input type="text" id="testStr" onblur="FullToDBC(this);" />
</center>
</body>
</html>
```