UPDATE 02/16/13
As the gentleman in the comments pointed out, it’s (practically) impossible to use a single regular expression to appropriately remove all comments from javascript (or any construct with strings), and I’d assume virtually impossible to do so even with a series of patterns. I suspect a full-fledged (but simple) parser is required, so here’s my stab at it:


end update…

If you just want the pattern, here ya go.

For the more curious…

This was surprisingly difficult, for the multiline comments anyways…

First thought:


Rougly translated into “slash star anything star slash”. But no – something about dot not catching new lines (even though in other cases it seems to do so just fine…)

So the next thought is “any number – or none – of spaces or non-spaces”:


I’m still not sure why, but this was gobbling up not just the comments (like it should) but large portions of stuff it shouldn’t be eating…

A search of SO lead me to this post, which looked almost identical to my last try, but added a “?” after the star…


Now AFAIK, the ? means “one of the preceding if available, ignore if not”… So /123?/ matches 123 and 12. The star means “any number or none of the preceding”, so /12*3/ matches 123 or 13, but not 12. So why does *? make it work? No idea…

Moving on… Single-line comments are obvious:


Which is “slash slash (anything) (end-of-line)”. The “end of line” needs the “m” (multiline) modifier to work (the “m” modifier means “treat line breaks as end of string” – if not present, the dollar sign matches the actual end of the string, not line breaks).

So they get married and have a baby:


And POC:

someString.replace(/(\/\*([\s\S]*?)\*\/)|(\/\/(.*)$)/gm, '');