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, "");
}
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With