看到一个牛人的博客
http://riny.net/lab/#tools_html2js
看了下他的代码 挺棒的
所依赖的两个库在这里 https://github.com/Bubblings/lab/tree/master/tools/js
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body> <style type="text/css">
body {
background-color: #fafafa;
}
.html2js {
width: 800px;
margin: 5px auto 0;
} #html, #javascript {
width: 790px;
height: 190px;
padding: 5px;
border: 1px solid #ccc;
box-shadow: 2px 2px 5px rgba(0,0,0,.1);
}
h2 {
text-align: center;
}
p {
margin: 10px 0;
line-height: 20px;
}
button {
margin-right: 5px;
}
#is-array {
margin: 0 3px 0 5px;
width: 13px;
height: 13px;
}
label {
display: inline-block;
}
select {
width: auto;
font-size: 14px;
}
</style> <div class="html2js">
<h2>html代码转javascript</h2>
<p>需要转换的html代码</p>
<textarea name="" id="html"></textarea>
<p>
<button class="btn btn-primary" id="single-btn">转单引号格式</button>
<button class="btn btn-primary" id="double-btn">转双引号格式</button>
<input type="checkbox" name="" id="is-array" checked><label for="is-array">数组拼接</label>
<select name="indent" id="indent">
<option value="1">制表符缩进</option>
<option value="2">2个空格缩进</option>
<option value="4" selected>4个空格缩进</option>
</select>
</p>
<p>生成的javascript代码</p>
<textarea name="" id="javascript"></textarea>
</div> <script src="htmlFormat.js"></script>
<script src="jsFormat.js"></script>
<script>
function html2js(html, quotes, isArray) {
var arr = html.split('\n');
var reg = new RegExp(quotes, 'g');
for (var i = arr.length - 1; i >= 0; i--) {
var cur = arr[i].replace(reg, '\\' + quotes); //假如我要转为的js字符串是单引号包裹的 那么html属性中的单引号需要转义
var startSpace = cur.match(/^\s*/g); //取到一行开头的空格(缩进)
cur = cur.replace(/^\s*|\s*$/, ''); //去掉开头和结尾的空格
if (cur === '') {
arr.splice(i, 1); //如果是空行 则丢弃 注意splice是在原有数组上操作的
continue;
}
cur = startSpace + quotes + cur + quotes;
arr[i] = cur;
}
if (isArray) {
return '[\n' + arr.join(',\n') + '\n].join('+ quotes + quotes +');'
} else {
return arr.join(' +\n') + ';';
}
} var htmlEle = document.getElementById('html');
var jsEle = document.getElementById('javascript');
var singleBtn = document.getElementById('single-btn');
var doubleBtn = document.getElementById('double-btn');
var checkbox = document.getElementById('is-array'); singleBtn.onclick = function () {
transform('\'');
}; doubleBtn.onclick = function () {
transform('\"');
}
/*
转换原理
先将html片段格式化
再将每一行的开头加上引号 (html中本身的引号要转义)
*/
function transform(quotes) {
var input = htmlEle.value;//.replace(/^\s*/, '');//去除开头的空格 //注意这里的input只有一行
var indentSize = document.getElementById('indent').value;
var indentChar = ' ';
if (indentSize == 1) {
indentChar = '\t';
}
input = style_html(input, indentSize, indentChar, 800); //格式化后的input //仍只有一行
jsEle.value = html2js(input, quotes, checkbox.checked);
}
</script>
</body>
</html>