首页  编辑  

JS中GBK十六进制hex转字符串

Tags: /计算机文档/网页制作/   Date Created:
<html>

<body>
<div>
<textarea id="input" placeholder="输入主机HEX字符串">BAA3B2E220202020404040</textarea ><br/>
<button type="button" onclick="convert()">GBK转字符串</button>
<button type="button" onclick="urlDecode()">URL解码</button>
<button type="button" onclick="urlEncode()">URL编码</button>
<button type="button" onclick="strEscape()">Java转义</button>
<button type="button" onclick="encodeBase64()">Base64编码</button>
<br/><textarea id="result" placeholder="转换结果"></textarea ><br/>
</div>
<style>
button {
background-color: #4CAF50; /* Green */
border: none;
color: white;
padding: 8px 10px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin-top: 10px;
margin-bottom: 10px;
margin-right: 10px;
}
textarea {
width:600px;
height:200px;
}
</style>
<script>

function gbkconvert(gbkStr, callback) {
var script = document.createElement('script');
script.id = 'gbkconvert';
script.src = 'data:text/javascript;charset=gbk,gbkconvertCb("' + gbkStr + '");';
document.body.appendChild(script);
window.gbkconvertCb = (res) => {
callback && callback(res);
};
}

function convert() {
var src = document.getElementById("input").value;
if (src.length % 2 != 0) return;
var s = '';
for (var i = 0; i < src.length; i+= 2) {
s += '%' + src.charAt(i) + src.charAt(i+1);
}
gbkconvert(s,(res) => {
document.getElementById("result").value = res;
}
)
}

function urlDecode() {
var s = document.getElementById("input").value;
document.getElementById("result").value = decodeURI(s);
}

function urlEncode() {
var s = document.getElementById("input").value;
document.getElementById("result").value = encodeURI(s);
}

function strEscape() {
var s = document.getElementById("input").value;
s = s.replace(/"/g, '\\"').replace(/\n/g, '\\n');
document.getElementById("result").value = s;
}

function encodeBase64() {
var s = document.getElementById("input").value;
s = decodeURIComponent(escape(atob(s)));
document.getElementById("result").value = s;
}

</script>

</body>
</html>