2013年7月29日 星期一

String 與 UTF-8 互轉

StringUTF-8

原始碼:
<table border="1" cellpadding="5" rules="all">
<tr><td>String</td><td>UTF-8</td></tr>
<tr><td><input id="str2utf8InputBoxy" size="30" value="123abcABC許功蓋" /></td><td><input id="str2utf8OutputBoxy" size="30" value="" /></td></tr>
<tr><td><button id="str2utf8ConvertBoxy">String to UTF-8</button></td><td><button id="utf8ToStrConvertBoxy">UTF-8 to String</button></td></tr>
</table>
<script type="text/javascript">
function $(id) {return document.getElementById(id.substr(1));}
var str2utf8 = function(word) {
    var output = "";
    for(key in word) {
        var dec = word[key].charCodeAt(0);
        if((dec>47 && dec<58) || (dec>64 && dec<91) || (dec>96 && dec<123)) {
            output += '%' + dec.toString(16);
        } else {
            output += encodeURIComponent(word[key]);
        }
    }
    return output;
};
$('#str2utf8InputBoxy').onclick = function() {
    $('#str2utf8InputBoxy').select();
};
$('#str2utf8OutputBoxy').onclick = function() {
    $('#str2utf8OutputBoxy').select();
};
$("#str2utf8ConvertBoxy").onclick = function() {
    $("#str2utf8OutputBoxy").value = str2utf8($("#str2utf8InputBoxy").value);
};
$("#utf8ToStrConvertBoxy").onclick = function() {
    $("#str2utf8InputBoxy").value = decodeURIComponent($("#str2utf8OutputBoxy").value);
};
</script>

後記:
此程式乃用來補足encodeURIComponent語法未包含數字與英文的UTF-8轉換問題。

沒有留言: