Created
December 18, 2012 14:48
-
-
Save sofish/4328620 to your computer and use it in GitHub Desktop.
using js to remove js comment
This file contains hidden or 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
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