Skip to content

Instantly share code, notes, and snippets.

@sofish
Created December 18, 2012 14:48
Show Gist options
  • Save sofish/4328620 to your computer and use it in GitHub Desktop.
Save sofish/4328620 to your computer and use it in GitHub Desktop.
using js to remove js comment
var nocomment = function(str) {
var div = document.createElement('div')
, inline = /([^\\])\/\/[^\n]*(\n?)/g
, reg = /\/[^\/]*\/g?m?i?[^\*]?/g
, commentLikeReg = /\/\\\/\*[^\/]*\*\//g
, string = new RegExp('(\'[^\']*\')|("[^"]*")','g')
, identifier = 'SOFISH_S_METHOD_TO_REMOVE_JS_COMMENTS_'
, matches = []
, counter = 0
, strReplace;
strReplace = function(reg, str) {
return str.replace(reg, function(match) {
matches.push(match);
return match.replace(match, identifier + (counter++));
})
}
str = str.replace(reg, function(match) {
var reg, type;
try {
reg = eval(match)
} catch(e) {}
type = Object.prototype.toString.call(reg);
return type === '[object RegExp]' ?
(matches.push(match), match.replace(match, identifier + (counter++))) :
match;
})
str = strReplace(string, str);
str = strReplace(commentLikeReg, str);
str = str.replace(/\/\*([^@])/g, '<!-- $1').replace(/[^@](\*\/)/g, ' -->');
str = str.replace(/(<!-- )[^>]*<!--/g, function(match, selected){
return match.replace(selected, '*');
});
div.innerHTML = str;
str = div.textContent;
str = str.replace(inline, function(match, g1, g2){
return match[0] + g2;
});
return str.replace(new RegExp(identifier + "(\\d+)", 'g'), function(match, selected) {
return matches[selected];
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment