UTF-8编码解码

  |   56 |   Code |   javascript WWW 字符编码

编码本来不准备写的,因为实现起来比较简单,不过平时有时侯自己要用。
网上那一堆,全部一模一样的效果,解个繁体出来都是乱码


源码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<input id="decode" name="lang" onclick="refresh()" type="radio" checked/>
<label for="decode" title="decode">解码</label>
<input id="encode" name="lang" onclick="refresh()" type="radio" />
<label for="encode" title="encode">编码</label>
<textarea style="width:80%;height:200px;" onkeyup="refresh();" id="toutf-8"></textarea>
<pre><code id="result" name="result"></code></pre>
<script>
var refresh = function()
{
    if(document.getElementById('decode').checked){
        document.getElementById("result").textContent="";
        var s=document.getElementById("toutf-8").value;
        var a=s.split(/%(?![A-Fa-f0-9]{2})/);
        for(i=0;i<a.length;i++){
            document.getElementById("result").textContent+=(decodeURIComponent(a[i]));
            if(i!=a.length-1)
                document.getElementById("result").textContent+="%";
        }
    }
    else document.getElementById("result").textContent=encodeURIComponent(document.getElementById("toutf-8").value);
}
refresh();
</script>
Comments
Write a Comment