Skip to content

Javascript comment stripper [closed]

I’m looking for some tool to remove cooments from Javascript sources. I was able to Google some, but none of them satisfied the following requirement: Everything else should be left as it is, in particular white space is not removed, BUT if a comment takes a whole line, the line is removed too.

Shortly, I want to be able to go from a nicely formatted source with comments to an equally formatted source without comments. Lines which only contain comments are removed, and traliing comments are removed together with the trailing spaces. All the rest is left as it is.

Do you know any tool for such a job?

EDIT: I try to be more specific. Using regular expressions is not possible, as the characters // or /* can also appear inside strings, regular expressions and so on.

The tool should take this input

var a = true;

//the following code is every useful
var b = 2;//really, really useful
 /**
Never, ever do this
var c = 3;
  */
var d = 4;

and give this output

var a = true;

var b = 2;
var d = 4;

Answer

Here’s some code I whipped up: Check it out: here

Also here is an example of my code you can test RIGHT NOW in a webpage

Here’s one I didn’t write that could be handy, though his code will fail on certain regex literals: http://james.padolsey.com/javascript/removing-comments-in-javascript/

EDIT: The code I wrote is as is. I am not updating it as it is something I wrote when I was a teenager and rather new to programming. If there is a bug, you can fix it.