java和javascript中全角字符串转为半角字符串

 java版本:

public static String toDBC(String str) {   
    if (str == null || str.length() == 0) {   
       return str;   
    }   
    char[] chars = str.toCharArray();   
    for (int i = 0; i < chars.length; i++) {   
       chars[i] = charToDBC(chars[i]);   
    }   
    return new String(chars);   
}   
protected static char charToDBC(char ch) {   
   if (ch == '\u3000') {   
        return '\u0020';// 半角空格:   
   } else if (ch > '\uFF00' && ch < '\uFF5F') {   
        return (char) (ch - 65248);   
    }   
    return ch;   
}  

javascript版本

function toDBC(str){   
  if (str) {   
       var result = "";   
       var code = 0;   
      for (var i = 0; i < str.length; i++) {   
            code = str.charCodeAt(i);   
           if (code == 12288) {   
               result += String.fromCharCode(32);   
          } else if (code > 65280 && code < 65375) {   
              result += String.fromCharCode(code - 65248);   
            } else {   
                result += str.charAt(i);   
           }   
        }   
        return result;   
    }   
    return str;   
}  

你可能感兴趣的:(java和javascript中全角字符串转为半角字符串)