Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for removing a /**/ comment in js

How do I remove something like this from a string using regex in JavaScript?

/*
    multi-line comment
*/

This is what I have tried:

var regex = /(\/\*(^\*\/)*\*\/)/g;
string = string.replace(regex, '');
like image 905
user2981107 Avatar asked Oct 15 '25 08:10

user2981107


1 Answers

If you'd like to match /* followed by any amount of text that does not contain */, followed by */, then you can use a regular expression, however it will not correctly remove block comments from JavaScript.

A simple example of where the pattern I described fails is:

var a = '/*'; /* block comment */

Note that the first /* will be matched even though it's contained in a string. If you can guarantee that the content you are searching within does not contain such inconsistencies, or are just using the regular expression to find places to make manual changes, then you should be reasonably safe. Otherwise, don't use regular expressions because they're the wrong tool for the job in this case; you have been warned.


To build the regular expression, you just have to break down my first sentence into its composite parts.

  • / starts the regular expression literal
  • \/\* matches the literal characters /*
  • [\s\S]*? matches any character in a non-greedy manner
  • \*\/ matches the literal characters */
  • / ends the regular expression

All together you end up with:

/\/\*[\s\S]*?\*\//

The non-greedy matching is necessary to prevent a close comment (*/) from getting captured when multiple block comments are in a file:

/* foo */
var foo = 'bar';
/* fizz */
var fizz = 'buzz';

With the non-greedy matching,

/* foo */

and

/* fizz */

would be matched, without the non-greedy matching,

/* foo */
var foo = 'bar';
/* fizz */

would be matched.

like image 67
zzzzBov Avatar answered Oct 18 '25 01:10

zzzzBov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!