2025-02-10

今天遇到個中文和英文標點之間轉換的問題
 
從網上找到一個解決方法記錄下
 
Html代碼 
<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"); 
                txttxt = 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> 

作者“Seth徐”
 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *