概述
第一种方案想用正则做答没成功,没有成功。
整理了下思路,已经完美解决(自认为完美)。
function codeFormat(code, indent, tmpIndent){
var indent = indent || ' ';
var tmpIndent = tmpIndent || 'n';
var preg = /]*)>([sS]*?)/ig;
return code.replace(preg, function($0, $1, $2, $3){
return tmpIndent + ''
+ codeFormat($3, indent, tmpIndent + indent)
+ ( $3.trim().substr(0,1) == '
+ '' + $1 + '>';
});
}
codeFormat("
This is a p
This is anothers p
This is a p
This is another p
/*
This is a p
This is anothers p
This is a p
This is another p
*/
codeFormat('
This is a p
This is another p
/*
----
--------
----
----
--------
------------
This is a p
------------
This is another p
--------
----
*/
以下是循环的老答案:
/*
感觉没什么难度,一个循环
遇见 >后跟
遇见 < 缩进
遇见 取消缩进
*/
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("
This is a p
This is another p
/*
This is a p
This is another p
*/
codeFormat('
This is a p
This is another p
/*
This is a p
This is another p
*/
最后
以上就是明理航空为你收集整理的html 字符串 规范化,HTML字符串排版的全部内容,希望文章能够帮你解决html 字符串 规范化,HTML字符串排版所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复