Skip to content

Instantly share code, notes, and snippets.

@badsyntax
Created September 29, 2010 16:45
Show Gist options
  • Save badsyntax/603087 to your computer and use it in GitHub Desktop.
Save badsyntax/603087 to your computer and use it in GitHub Desktop.
(function(window, document, undefined){
// !incomplete
var comments = [];
function hideComments(content){
var c = -1;
return content
.replace(/(\/\/.*?)\n/g, '__c{$1}') // find '// comment' and replace with placeholder
.replace(/\n/g,'\uffff') // replace new lines chars so we can match over multi lines
.replace(/(\/\*.*?\*\/)/g, '__c{$1}') // find '/* comment */' and replace with placeholder
.replace(/__c\{(.*?)\}/g, function(x, y){ // find placeholder comment and store comment content
comments[++c] = y;
return '__c{' + c + ';}';
})
.replace(/\uffff/g,'\n'); // replace newline placeholder with actual newline
}
function restoreComments(content){
return content
.replace(/__c\{([0-9]+);\}/g, function(x, y){ // find placeholder comments and replace with comment content
return '\n' + comments[y].replace(/\uffff/g,'\n') + '\n';
});
}
function cleanWhitespace(content){
return content
.replace(/\s/g, ' ') // convert all whitespace to normal space char
.replace(/ {2,}/g, ' ') // convert multiple consecutive space chars to one space char
.replace(/([:;]) /g, '$1') // remove space after semi-colons
.replace(/ ([:;])/g, '$1') // remove space before semi-colons
.replace(/\s+([\{\}])/g, '$1') // remove space before braces
.replace(/([\{\}])\s+/g, '$1') // remove space after braces
.replace(/\}/g, '}\n') // add newline after brace
.replace(/([^;])\}/g, '$1;}') // add semicolon before brace
;
}
document.getElementById('clean').onclick = function(){
var content = document.getElementById('content').value;
content = hideComments(content);
content = cleanWhitespace(content);
content = restoreComments(content);
document.getElementById('content').value = content;
};
})(window, document);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment