JavaScript character and Unicode conversion Chinese character to Unicode code

Posted by georgen on Wed, 01 Apr 2020 11:49:41 +0200

Unicode is an industry standard in the field of computer science. JavaScript itself is written using the Unicode character set,
Sometimes we need to transcode the obtained value when we need to rearrange and compile a piece of text or content,
Make a note,

In fact, it mainly uses the charCodeAt() method and escape() function of JS
For details, please click the following website:
http://www.w3school.com.cn/jsref/jsref_charCodeAt.asp

http://www.w3school.com.cn/jsref/jsref_escape.asp

Code:

<!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">Character rotation Unicode</button>

<div id="show1"></div>


<input id="input2" type="text">

<button id="btn2">Unicode Turn character</button>

<div id="show2"></div>


<script>
    function $(id) {
        var value = document.getElementById(id);

        return value;
    }

    // Turn to the Unicode codeacharcodeat() method to return the Unicode encoding of the character at the specified location. The return value is an integer between 0 and 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");
    }

    // The unicode escape() function encodes strings
    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>

Rendering after execution:

In addition, an online transcoding website is provided:
http://tool.chinaz.com/tools/unicode.aspx

Topics: Javascript encoding