JavaScript 字符串转 Unicode 编码的十六进制形式

在这里插入图片描述

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>字符串转 Unicode 编码</title>
        <style type="text/css">
            body {
                font-family: "courier new";
            }
            input, textarea {
                margin: 5px;
            }
        </style>
    </head>
    <body>
        <textarea id="text" placeholder="input" style="width: 200px; height: 80px;"></textarea>
        <br />
        <input type="button" id="clear" value="clear" />
        <input type="button" id="to" value="String to Unicode" />
        <br />
        <textarea id="unicode" placeholder="output" style="width: 200px; height: 320px;"></textarea>
        
        <script src="js/jquery-3.4.1.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                // 清空输入、输出
                $("#clear").click(function() {
                    $("#text").val("");
                    $("#unicode").val("");
                });
                
                // 字符串转 Unicode 编码
                $("#to").click(function() {
                    var text = $("#text").val();
                    $("#unicode").val(stringToHex(text));
                });
            });
            
            // 字符串转 Unicode 编码的十六进制形式
            function stringToHex(str) {
                var hex = "";
                for (var i = 0; i < str.length; i++) {
                    // charCodeAt() 方法返回字符串中指定索引的字符 Unicode 编码
                    var code = str.charCodeAt(i);
                    // 十进制转十六进制
                    hexCode = code.toString(16).toUpperCase();
                    // 不足 4 位十六进制数的,补零凑足 4 位
                    var padding = "0000";
                    var length = padding.length - hexCode.length;
                    // 拼接
                    hex += padding.substr(0, length) + hexCode;
                }
                return hex;
            }
        </script>
    </body>
</html>
发布了36 篇原创文章 · 获赞 0 · 访问量 1870

猜你喜欢

转载自blog.csdn.net/qq_29761395/article/details/103762052