Artem Gassan
Artem Gassan

Reputation: 31

Remove JavaScript comments from string with C#

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);

Upvotes: 3

Views: 4916

Answers (5)

Rush Frisby
Rush Frisby

Reputation: 11454

content = Regex.Replace(content,
                        "/\\*.*?\\*/",
                        String.Empty,
                        RegexOptions.Compiled | RegexOptions.Singleline);

Upvotes: -1

hlovdal
hlovdal

Reputation: 28198

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.

Upvotes: -1

bobince
bobince

Reputation: 536429

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.

Upvotes: 7

Christian C. Salvad&#243;
Christian C. Salvad&#243;

Reputation: 827486

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); 

Upvotes: 4

Marko Dumic
Marko Dumic

Reputation: 9888

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)

Upvotes: 6

Related Questions