tags:

views:

1558

answers:

4

I am trying to remove javascript comments (// and /**/) from sting with C#. Does anyone have RegEx for it. I am reading list of javascript files then append them to string and trying to clean javascript code and make light to load. Bellow you will find one of the RegEx that works fine with /* */ comments but I need to remove // comments too:

content = System.Text.RegularExpressions.Regex.Replace(content,
    @"/\*[^/]*/", 
    string.Empty);
+7  A: 

If you want to minify Javascript files ("make it light to load"), why not try JSMin by Douglas Crockford? There is link to c# implementation at the bottom of the page (http://www.crockford.com/javascript/jsmin.cs)

Marko Dumic
+5  A: 

An alternative to Regex can be the YUI Compressor for .Net, which can allow you to remove comments and minify JavaScript code.

// Note: string javaScript == some javascript data loaded from some file, etc.
compressedJavaScript= JavaScriptCompressor.Compress(javaScript);
CMS
I might be a little biased, but I'd recommend this also. Just wish i can fix my last little bug with this project *sigh ... and hint hint for some pro-help ? :) *
Pure.Krome
I'll vouch for YUI Compressor for .NET. I've integrated it into my build process - I automatically generate a myfile.min.js file from each myfile.debug.js. It is awesome.
Greg
+6  A: 

You can't use a simple regex to remove comments from JS - at least not reliably. Imagine, for example, trying to process stuff like:

alert('string\' // not-a-comment '); // comment /* not-a-nested-comment
alert('not-a-comment'); // comment */* still-a-comment
alert('not-a-comment'); /* alert('commented-out-code');
// still-a-comment */ alert('not-a-comment');
var re= /\/* not-a-comment */; //* comment
var e4x= <x>// not-a-comment</x>;

You can make your regex work better than it does now by making it end on '*/' instead of just '/', and wrapping an or-clause around to it add the test for // up to the newline. But it'll never be bulletproof, because regex does not have the power to parse languages like JavaScript or [X]HTML.

bobince
A: 

I recommend the program stripcmt:

StripCmt is a simple utility written in C to remove comments from C, C++, and Java source files. In the grand tradition of Unix text processing programs, it can function either as a FIFO (First In - First Out) filter or accept arguments on the commandline.

simple and robust, does the job flawlessly.

hlovdal