1. 程式人生 > >JavaScript 字元與Unicode 轉換 漢字轉Unicode碼

JavaScript 字元與Unicode 轉換 漢字轉Unicode碼

Unicode 是電腦科學領域裡的一項業界標準,JavaScript本身就是使用Unicode字符集編寫的,
有時候我們需要對一段文字或者一段內容進行重新排版編譯的時候就需要將獲取的值進行轉碼,
做個隨筆記錄一下,

程式碼:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #show1,#show2{
            width
:200px
; height:100px; margin: 15px 0; border: 1px solid #aaf; }
</style> </head> <body> <input id="input1" type="text"> <button id="btn1">字元轉Unicode</button> <div id="show1"></div> <input id="input2" type
="text">
<button id="btn2">Unicode轉字元</button> <div id="show2"></div> <script> function $(id) { var value = document.getElementById(id); return value; } // 轉為unicode 編碼 charCodeAt() 方法可返回指定位置的字元的 Unicode 編碼。返回值是 0 - 65535 之間的整數。 function
toUnicode(str) {
var res = []; for ( var i=0; i<str.length; i++ ) { res[i] = ( "00" + str.charCodeAt(i).toString(16) ).slice(-4); } return "\\u" + res.join("\\u"); } // unicode轉字元 escape() 函式可對字串進行編碼 function toStr(str){ str = str.replace(/(\\u)(\w{1,4})/gi,function(v){ return (String.fromCharCode(parseInt((escape(v).replace(/(%5Cu)(\w{1,4})/g,"$2")),16))); }); str = str.replace(/(&#x)(\w{1,4});/gi,function(v){ return String.fromCharCode(parseInt(escape(v).replace(/(%26%23x)(\w{1,4})(%3B)/g,"$2"),16)); }); str = str.replace(/(&#)(\d{1,6});/gi,function(v){ return String.fromCharCode(parseInt(escape(v).replace(/(%26%23)(\d{1,6})(%3B)/g,"$2"))); }); return str; } $("btn1").onclick=function () { $("show1").innerHTML=toUnicode($("input1").value); }; $("btn2").onclick=function () { $("show2").innerHTML=toStr($("input2").value); }
</script> </body> </html>

執行後效果圖:
這裡寫圖片描述