问题
I am writing a javascript function which can tidy up html code. (javascript and css code tidying not necessary in the moment)
Here is my code. And check it on http://jsfiddle.net/2q26K/
function tidyHtml(html) {
var html = html.trim().replace(/>[^<]+</gm, function ($1) {
return '>' + $1.substr(1, $1.length - 2).trim() + '<';
}).replace(/>\s+</gm, '><');
var containerElement = document.createElement('div');
containerElement.innerHTML = html;
var result = containerElement.innerHTML;
var findLevel = function (child, parent) {
var level = 0;
while (child != parent) {
child = child.parentNode;
level++;
}
return level;
}
Array.prototype.slice.call(containerElement.getElementsByTagName('*')).forEach(function (element) {
var tabs = new Array(findLevel(element, containerElement) - 1).join(' '),
tabs2 = (element.parentNode.lastChild == element) ? ('\n' + tabs.substring(0, tabs.length - 1)) : '',
containerElement = document.createElement('div');
containerElement.appendChild(element.cloneNode(true));
result = result.replace(containerElement.innerHTML, '\n' + tabs + containerElement.innerHTML + tabs2);
});
return result;
}
In the example provided, it works perfectly.
But, sometimes when html code like that: http://jsfiddle.net/2q26K/1/
It refuses to change
<div id="hlogo">
<a href="/">Stack Overflow</a>ABC</div>
To
<div id="hlogo">
<a href="/">Stack Overflow</a>ABC
</div>
Cannot solve it. It's too complicated. Is there any easier method that can do the same thing?
Any suggestion to improve my code, or any example that I can learn from?
回答1:
You can use this I've found it in 11346108
回答2:
If speed is not an issue, you coul run jquery parser (alternatively cheerio with node) on your generated html string, using the $( String ).html() method as explained here
来源:https://stackoverflow.com/questions/20313153/tidy-html-code-based-on-javascript