Skip to content

Instantly share code, notes, and snippets.

@cyjake
Created April 20, 2012 07:54
Show Gist options
  • Save cyjake/2426984 to your computer and use it in GitHub Desktop.
Save cyjake/2426984 to your computer and use it in GitHub Desktop.
A Simple HTML formatter in JavaScript
define(function(require, exports) {
var TAB_WIDTH = 2;
var str_helper = require('./string');
function squeeze(str) {
return str.replace(/^[ \n\t]+/, '').replace(/\>[\n\t ]+/g, '>');
}
exports.indent = function(html) {
var chr, i, chrs = squeeze(html).split(''),
result = '',
level = 0,
indent = '',
pInTag,
pCloseTag,
tagName;
for (i = 0; i < chrs.length; i++) {
chr = chrs[i];
if (chr === '<') {
pCloseTag = chrs[i+1] === '/';
if (pCloseTag) {
level--;
indent = str_helper.multi(' ', level * TAB_WIDTH);
}
result += '\n' + indent + '<';
}
else if (chr === '>') {
tagName = getTagName(chrs, i-1);
pInTag = !pCloseTag && chrs[i-1] !== '/' && tagName !== 'img' && tagName !== 'br';
pCloseTag = false;
if (pInTag) {
level++;
}
indent = str_helper.multi(' ', level * TAB_WIDTH);
result += '>\n' + indent;
}
else {
result += chr;
}
}
function getTagName(chrs, i) {
var chr = chrs[i],
ret = '';
while (chr !== '<') {
ret = chr + ret;
chr = chrs[i--];
}
return ret.substr(0, ret.indexOf(' '));
}
return result.replace(/\n *\n/g, '\n');
};
exports.squeeze = squeeze;
exports.escape = function(str) {
return str.replace(/\</g, '&lt;').replace(/\>/g, '&gt;');
};
});
define(function(require, exports) {
function multi(str, spaces) {
var i, indent = '';
for (i = 0; i < spaces; i++) {
indent += ' ';
}
return indent;
}
exports.multi = multi;
exports.indent = function(str, spaces) {
var indent = multi(' ', spaces);
return str.replace(/^/g, indent).replace(/\n/g, '\n' + indent);
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment