How to convert javascript unicode notation code to utf-8?

41,709

Solution 1

You use the below javascript function to convert unicode to utf-8

function encode_utf8( s ){
    return unescape( encodeURIComponent( s ) );
}( '\u4e0a\u6d77' )

You can also try it out in firebug console. It works.

Solution 2

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
    <title>UTF-8 To Unicode</title>
    <style type="text/css">
    <!--
    td {
        height: 24px;
        line-height: 24px;
    }
    #content {
        margin-top: 2px;
    }
    -->
    </style>
    </head>
    <script type="text/javascript">
        function encodeGB2312(){
            var c = document.all.content.value;
            var re = /(%)+/g;
            var result =  escape(c);
            document.all.content.value =  result.replace(re, "\\");
            document.all.content.focus();
            document.all.content.select();
        }
        function clearContent(){
            document.all.content.value = "";
            document.all.content.focus();
        }
    </script>

    <body>
        <h3 align="center">UTF-8 To Unicode</h3>
        <table width="600" border="1" cellspacing="0" cellpadding="0" align="center"         style="text-align:center;">
          <tr>
            <td>Input what you want to convert:</td>
            <td><input type="text" name="content" id="content" size="50"/></td>
          </tr>
          <tr>
            <td colspan="2">
            <input type="button" name="encoding" value="Start Conversion"         onclick="encodeGB2312()"/>&nbsp;&nbsp;&nbsp;&nbsp;
            <input type="button" name="clear" value=" Cancel" onclick="clearContent();"/></td>
          </tr>
        </table>
    </body>
    </html>

This is a sample of convert utf-8 to unicode, do it in turn.

Share:
41,709
Leon
Author by

Leon

An old PHP developer, trying to learn SwiftUI. Any oppotunity to work as a SwiftUI developer is welcomed.

Updated on July 30, 2020

Comments

  • Leon
    Leon over 3 years

    Is there a command line tool or online service that can convert javascript unicode notation code to utf-8?

    E.g. I got this json code, but it is hard to edit in common text editor.

    {"name":"leon zhang","city":"\u4e0a\u6d77"}
    

    I want to convert it to:

    {"name":"leon zhang","city":"上海"}
    
  • Paul Bellora
    Paul Bellora over 11 years
    Sorry to nag but this is an English language site - please translate your explanation to that language.