<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>报文转换</title>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<h1>报文转换</h1>
<textarea rows="15" cols="100" id="oldMessage" placeholder="输入报文......"></textarea>
<br/>
<br/>
<button id="up2Low">大写下滑转驼峰</button>
<button id="low2Up">驼峰转大写下滑</button>
<br/>
<br/>
<textarea rows="15" cols="100" id="newMessage" placeholder="输出报文......"></textarea>
<br/>
<div id="footer" style="text-align: center;">
Copyright © 2020 wangmw
</div>
</body>
</html>
<script type="text/javascript">
$(document).ready(function(){
var up2Low = function(msg) {
var newMsg = ""
var msgArr = msg.split("_");
for(i = 0;i < msgArr.length; i++) {
if(i == 0) {
newMsg = msgArr[i].toLowerCase();
}else {
var addMsg = msgArr[i];
newMsg = newMsg + addMsg.substring(0, 1).toUpperCase() + addMsg.substring(1).toLowerCase();
}
}
return newMsg;
}
var low2Up = function(msg) {
var newMsg = ""
// 从第2个位置开始循环字符串
if(msg.length > 1) {
newMsg = msg.substring(0, 1);
for (var i = 1; i < msg.length; i++) {
var s = msg.substring(i, i + 1);
// 在大写字母前添加下划线
if (s == s.toUpperCase() && (/^[0-9A-Z]*$/.test(s.charAt(0)))) {
newMsg += "_";
}
// 其他字符直接转成大写
newMsg += s;
}
}else {
newMsg = msg;
}
return newMsg.toUpperCase();
}
var convertJson = function(jsonMsg,type) {
// 判断jsonMsg是不是json对象
if(jsonMsg instanceof Array) {
var resultJson = [];
for(i = 0; i < jsonMsg.length; i++) {
resultJson.push(convertJson(jsonMsg[i],type));
}
return resultJson;
}else if(jsonMsg instanceof Object) {
var resultJson = {};
for(var item in jsonMsg){
// 将item进行转换
var jValue=jsonMsg[item];//key所对应的value
if("1" == type) {
// 大写下滑转驼峰
item = up2Low(item);
}else {
// 驼峰转大写下滑
item = low2Up(item);
}
try{
// 判断字符串是否是纯数字
var reg = /^[0-9]+.?[0-9]*$/;
console.info(jValue);
console.info(typeof jValue);
if (jValue instanceof Object) {
jValue = convertJson(jValue,type);
}
resultJson[item] = jValue;
}catch(e){
resultJson[item] = jValue;
}
}
return resultJson;
}else {
return jsonMsg;
}
}
$("#up2Low").on("click",function() {
var oldMessage = $("#oldMessage").val();
// 将字符串转换成json对象
debugger;
var jsonMsg = "";
try{
jsonMsg = eval('(' + oldMessage+ ')');
jsonMsg = convertJson(jsonMsg,"1");
jsonMsg = JSON.stringify(jsonMsg);
}catch(e){
jsonMsg = up2Low(oldMessage);
}
console.info(jsonMsg);
$("#newMessage").val(jsonMsg);
});
$("#low2Up").on("click",function() {
var oldMessage = $("#oldMessage").val();
// 将字符串转换成json对象
debugger;
var jsonMsg = "";
try{
jsonMsg = eval('(' + oldMessage+ ')');
jsonMsg = convertJson(jsonMsg,"2");
jsonMsg = JSON.stringify(jsonMsg);
}catch(e){
jsonMsg = low2Up(oldMessage);
}
console.info(jsonMsg);
$("#newMessage").val(jsonMsg);
});
});
</script>