Created
April 20, 2012 07:54
-
-
Save cyjake/2426984 to your computer and use it in GitHub Desktop.
A Simple HTML formatter in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, '<').replace(/\>/g, '>'); | |
}; | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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