把中文标点替换成英文,全角标点替换成半角

今天遇到个中文和英文标点之间转换的问题

 

从网上找到一个解决方法记录下

 

<html>
<head>
<script language="javascript">
		function ChineseToEnglish(txt)  
        {  
            var ChineseInterpunction = [ "“", "”", "‘", "’", "。", ",", ";", ":", "?", "!", "……", "—", "~", "(", ")", "《", "》" ];  
            var EnglishInterpunction = [ "\"", "\"", "'", "'", ".", ",", ";", ":", "?", "!", "…", "-", "~", "(", ")", "<", ">" ];  
			for (var j = 0; j < ChineseInterpunction.length; j++)  
			{  
				//alert("txt.replace("+ChineseInterpunction[j]+", "+EnglishInterpunction[j]+")");
				var reg=new RegExp(ChineseInterpunction[j],"g");
				txt = txt.replace(reg, EnglishInterpunction[j]); 
			} 
			alert(txt);
            return txt;
        } 

   //方法描述:把指定输入框中的全角字符转为半角字符,并在输入框失去焦点时自动改变输入框中的全角字符
  //原理说明:
  //      1、全角空格为12288,半角空格为32
   //      2、其他字符半角(33-126)与全角(65281-65374)的对应关系是:均相差65248
        function FullToDBC(obj){
                var Str = obj.value;
                var DBCStr = "";
				Str = ChineseToEnglish(Str);
				if(/.*[\u4e00-\u9fa5]+.*$/.test(Str)){       
					alert("含有汉字!");       
				}
                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>
		<textarea id="testStr" rows="20" cols="120" onblur="FullToDBC(this);"></textarea>
</center>
</body>
</html>
 

你可能感兴趣的:(中英文标点转化)