Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript regular expression - removing comments

The example is from eloquent javascript book.Although There's a little explanation in the book it's really hard to follow, can anyone explain it from beginner perspective.I am having hard time to follow which slash is for what.

function stripComments(code) {
  return code.replace(/\/\/.*|\/\*[^]*\*\//g, "");
}
like image 482
Wahid Polin Avatar asked Feb 12 '26 19:02

Wahid Polin


2 Answers

Comment can have two forms:

// this is a comment
/* this is a comment */

Unfortunately, both / and * are special characters in regular expressions, so they must be escaped.

So we start with an empty match expression

//g

We set it to match the first form, // followed by any number of characters, which would be //.* but the slashes have to be escaped

/\/\/.*/g

The other form, /* followed by anything followed by */ is /*[^]**/ but we have to escape the literal slashes and asterisks

\/\*[^]*\*\/

The two forms are then combined with a | character which denotes a "or":

\/\/.*|\/\*[^]*\*\/

and inserted into the empty regex

/\/\/.*|\/\*[^]*\*\//g
like image 70
Jean-Karim Bockstael Avatar answered Feb 15 '26 10:02

Jean-Karim Bockstael


First and last slashes are delimiters.

g at the end is a modifier (Modifiers are used to perform case-insensitive and global searches) and performs a global match (find all matches rather than stopping after the first match).

| means OR.

\/\/.* has some escaped chars and can be translated as // followed by any characters \/\*[^]*\*\/ has also some escaped chars and can be translated as /*any characters*/

Note: both / and * must be escaped because they are used by regex syntax (special characters). So \/ means / and \* means * while .* means any characters (0 or more times)

Since the goal of your code is to remove comments, all comments like // xxxx or /* xxx */ are replaced by empty string

like image 22
Justin Iurman Avatar answered Feb 15 '26 08:02

Justin Iurman



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!