javascript - HTML字符串排版
本文介绍了javascript - HTML字符串排版的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
我现在有HTML
代码的字符串,想要对字符串进行排版,有没有什么可用的方法?
需要一款js插件,或者方法,能在项目里面转换用的。
比如原字符串是:
<div><p>This is a p</p><p>This is another p</p></div>
添加空格和换行,变成新的字符串:
<div>
<p>This is a p</p>
<p>This is another p</p>
</div>
解决方案
第一种方案想用正则做答没成功,没有成功。
整理了下思路,已经完美解决(自认为完美)。
function codeFormat(code, indent, tmpIndent){
var indent = indent || ' ';
var tmpIndent = tmpIndent || '\n';
var preg = /<(\S*)([^>]*)>([\s\S]*?)<\/\1>/ig;
return code.replace(preg, function($0, $1, $2, $3){
return tmpIndent + '<' + $1 + $2 + '>'
+ codeFormat($3, indent, tmpIndent + indent)
+ ( $3.trim().substr(0,1) == '<' ? tmpIndent : '')
+ '</' + $1 + '>';
});
}
codeFormat("<div><p>This is a p</p><p>This is anothers p</p></div><div><p>This is a p</p><p>This is another p</p></div>");
/*
<div>
<p>This is a p</p>
<p>This is anothers p</p>
</div>
<div>
<p>This is a p</p>
<p>This is another p</p>
</div>
*/
codeFormat('<html><head><title></title></head><body class="haha"><div style="background:#C00;"><p>This is a p</p><p>This is another p</p></div></body></html>', '----');
/*
<html>
----<head>
--------<title></title>
----</head>
----<body class="haha">
--------<div style="background:#C00;">
------------<p>This is a p</p>
------------<p>This is another p</p>
--------</div>
----</body>
</html>
*/
以下是循环的老答案:
/*
感觉没什么难度,一个循环
遇见 >后跟<,换行
遇见 < 缩进
遇见 </ 取消缩进
*/
function codeFormat(code, indent){
var indent = indent || " "; //缩进字符
var tmpIndent = ""; //保存代码字符串
var result = "", key = "", keyNext = "";
for( var i = 0 ; i < code.length ; i++ ){
key = code[i];
keyNext = i < code.length-1 ? code[i+1] : "";
if(key == "<"){
if( keyNext == "/" ){
tmpIndent = tmpIndent.substr(indent.length);
}
if( result[result.length-1] == "\n" ){
result += tmpIndent;
}
if( keyNext != "/" ){
tmpIndent += indent;
}
}
result += key;
if(key == ">" && keyNext == "<" ){
result += "\n";
}
}
return result;
}
codeFormat("<div><p>This is a p</p><p>This is another p</p></div>");
/*
<div>
<p>This is a p</p>
<p>This is another p</p>
</div>
*/
codeFormat('<html><head><title></title></head><body class="haha"><div style="background:#C00;"><p>This is a p</p><p>This is another p</p></div></body></html>', ' ');
/*
<html>
<head>
<title>
</title>
</head>
<body class="haha">
<div style="background:#C00;">
<p>This is a p</p>
<p>This is another p</p>
</div>
</body>
</html>
*/
这篇关于javascript - HTML字符串排版的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文