string encoding

  1. Convert a Unicode number into a character
  2. Encode a URI
  3. decodes an encoded string

1.Convert a Unicode number into a character

JavaScript String fromCharCode() Method

<!DOCTYPE html>
<html>

<body>
    <p id="demo"></p>

    <script>
     var res = String.fromCharCode(65, 40,57,89,111,106,108,42,105,49,53,54);
        document.getElementById("demo").innerHTML = res;
    </script>

</body>

</html>

จะได้

A(9Yojl*i156

แต่ถ้าจะอ่าน Unicode จาก string ใช้ charCodeAt

<!DOCTYPE html>
<html>

<body>
    <script>
        var str = "HELLO WORLD";
        var n = str.charCodeAt(0);
        document.write(n)
    </script>
</body>

</html>

จะได้ 72

2.Encode a URI

JavaScript encodeURI() Function

<!DOCTYPE html>
<html>

<body>
    <p id="demo"></p>

    <script>
        var uri = "my test.asp?name=ståle&car=saab";
        var res = encodeURI(uri);
        document.getElementById("demo").innerHTML = res;
    </script>

</body>

</html>

จะได้

my%20test.asp?name=st%C3%83%C4%A8le&car=saab

3.decodes an encoded string

JavaScript unescape() Function

<!DOCTYPE html>
<html>

<head>
    <script>
        var str = "Need tips? Visit W3Schools!";
        var str_esc = escape(str);
        document.write(str_esc + "<br>")
        document.write(unescape(str_esc))
    </script>
</head>

<body>
</body>

</html>

รันแล้วจะได้

Need%20tips%3F%20Visit%20W3Schools%21
Need tips? Visit W3Schools!

เปรียบเทียบการใช้ encodeURI และ escape

<!DOCTYPE html>
<html>

<body>
    <p id="demo"></p>

    <script>
        var uri = "my test.asp?name=ståle&car=saab";
        var res = encodeURI(uri) + "<br>" + escape(uri);;
        document.getElementById("demo").innerHTML = res;
    </script>

</body>

</html>

จะได้

my%20test.asp?name=st%C3%A5le&car=saab
my%20test.asp%3Fname%3Dst%E5le%26car%3Dsaab