美文网首页
unicode 中文互转。

unicode 中文互转。

作者: Hoistthecolors | 来源:发表于2018-01-25 13:42 被阅读31次

直接上demo代码。运行一下就ok。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>string to unicode</title>
</head>
<style type="text/css">
    *{
        padding: 0;
        margin: 0;
    }
    div{
        width: 500px;
        height: 80px;
        border: 1px solid red;
    }
    .btn {
        margin: 20px 0;
    }
</style>
<body>
    输入中文<input type="text" class="input">
    <button class="btn1">转化unicode</button>
    <div class="string unicode-box">
    </div>
    <button class="btn2">unicode转中文</button>
    <div class="string string-box">
    </div>
</body>
<script type="text/javascript" src='jquery-1.8.3.min.js'></script>
<script type="text/javascript">
    $(function() {
        $('.btn1').on('click', function() {
            var s = $('.input').val();
            $('.unicode-box').text(toUnicode(s))
        })

        $('.btn2').on('click', function() {
            var s = $('.unicode-box').text();
            $('.string-box').text(toChinese(s))
        })
    })

    function toUnicode(str) {
        if (!str) {
            return;
        }else{
            var res = [];  
            for ( var i=0; i<str.length; i++ ) {  
                res[i] = ( "00" + str[i].charCodeAt().toString(16) ).slice(-4);  
            }  
            return "\\u" + res.join("\\u");  
        }
    } 
    function toChinese (unicode) {
        var unicodeString = unicode.replace(/\\/g, "%");  
        return unescape(unicodeString);  
    }

</script>
</html>

相关文章

网友评论

      本文标题:unicode 中文互转。

      本文链接:https://www.haomeiwen.com/subject/cprvaxtx.html