js编码转换工具

时间:2021-12-13 18:24:20
 
<!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=utf-8" />
<title>编码转换工具</title>
<script type="text/javascript">
//转换成ASCII码
function ascii(str) {
return str.replace(/[^\u0000-\u00FF]/g,
function($0) {
return escape($0).replace(/(%u)(\w{4})/gi, "\&#x$2;")
});
}

//转换成Unicode编码
function unicode(str) {
return str.replace(/[^\u0000-\u00FF]/g,
function($0) {
return escape($0).replace(/(%u)(\w{4})/gi, "\\u$2")
});
}

//转换成中文
function reconvert(str) {
//Unicode
str = str.replace(/(\\u)(\w{4})/gi,
function($0) {
return (String.fromCharCode(parseInt((escape($0).replace(/(%5Cu)(\w{4})/g, "$2")), 16)));
});

//ASCII
str = str.replace(/(&#x)(\w{4});/gi,
function($0) {
return String.fromCharCode(parseInt(escape($0).replace(/(%26%23x)(\w{4})(%3B)/g, "$2"), 16));
});
return str;
}

//中文转换为Asc2
function chToAsc2(){
var content = document.getElementById("ctoas");
var asc2Value = ascii(content.value);
document.getElementById("ctoat").value=asc2Value;
}

//中文转换为Unicode
function chToUnicode(){
var content = document.getElementById("ctous");
var unicodeValue = unicode(content.value);
document.getElementById("ctout").value=unicodeValue;
}

//Unicode或Asc2反转为中文
function codeToCh(){
var content = document.getElementById("ctocs");
var chValue = reconvert(content.value);
document.getElementById("ctoct").value=chValue;
}
</script>
</head>

<body>
<!--中文转换成ASCII-->
<div id="chtoasc2">
<h1>中文转ASCII</h1>
<textarea id="ctoas" name="ctoas" rows="5" cols="50"></textarea><br/>
<input type="button" value="中文转ASCII" onclick="chToAsc2();"/><br/>
<textarea id="ctoat" name="ctoat" rows="5" cols="50"></textarea><br/>
</div>

<!--中文转换成Unicode-->
<div id="chtounicode">
<h1>中文转Unicode</h1>
<textarea id="ctous" name="ctous" rows="5" cols="50"></textarea><br/>
<input type="button" value="中文转Unicode" onclick="chToUnicode();"/><br/>
<textarea id="ctout" name="ctout" rows="5" cols="50"></textarea><br/>
</div>

<!--Unicode或ASCII编码翻转为中文-->
<div id="ctoch">
<h1>反转为中文</h1>
<textarea id="ctocs" name="ctocs" rows="5" cols="50"></textarea><br/>
<input type="button" value="反转为中文" onclick="codeToCh();"/><br/>
<textarea id="ctoct" name="ctoct" rows="5" cols="50"></textarea><br/>
</div>
</body>
</html>