圓角與半角互相轉換

   最近發現客戶在輸入序列號時,常常輸入圓角。致使下載不了應用。下面這段js能夠將圓角字符轉成半角,將半角轉成圓角。javascript

原理很簡單,就兩條:java

一、全角空格爲12288,半角空格爲 32  函數

二、其餘字符半角(33-126)與全角 (65281-65374)的對應關係是:均相差65248blog

故代碼以下:ip

//半角轉換爲全角函數 
function ToDBC(txtstring) {
    var tmp = "";
    for (var i = 0; i < txtstring.length; i++) {
        if (txtstring.charCodeAt(i) == 32) {
            tmp = tmp + String.fromCharCode(12288);
        }
        if (txtstring.charCodeAt(i) < 127) {
            tmp = tmp + String.fromCharCode(txtstring.charCodeAt(i) + 65248);
        }
    }
    return tmp;
}
//全角轉換爲半角函數 
function ToCDB(str) {
    var tmp = "";
    for (var i = 0; i < str.length; i++) {
        if (str.charCodeAt(i) > 65248 && str.charCodeAt(i) < 65375) {
            tmp += String.fromCharCode(str.charCodeAt(i) - 65248);
        }
        else {
            tmp += String.fromCharCode(str.charCodeAt(i));
        }
    }
    return tmp
}
相關文章
相關標籤/搜索