๐ฐgreedy vs. lazy
๐ง under construction
regex matches
------------------------------------------------------
+ b\w+ be bee beer beers (greedy)
โฐโฏ โฐโโฏ โฐโโโฏ โฐโโโโฏ
+? b\w+? be bee beer beers (lazy)
โฐโฏ โฐโฏ โฐโฏ โฐโฏ// greedy: [^]* or
// โ โญโโโฎ <--- greedy (as many as possible)
const commentPattern = /\/\/.*|\/\*[^]*\*\//g;
// โฐโ1โโโฏ โฐโโโโโ2โโโโโโฏ
// 1. '//' followed by any non-newline characters.
// 2. '/*' followed by any characters and '*/'.
// lazy: [^]*?
const commentPattern2 = /\/\/.*|\/\*[^]*?\*\//g;
// โฐโโโโฏ <--- lazy (as few as possible)
// remove comments from code
function stripComments(code, lazy = false) {
let pattern = commentPattern;
if (lazy) pattern = commentPattern2;
return code.replace(pattern, "");
}
stripComments("1 + /* 2 */ 3"), // '1 + 3'
stripComments("x = 10; // ten!"), // 'x = 10; '
stripComments("1 /* a */ + /* b */ 1"), // '1 1' // greedy
stripComments("1 /* a */ + /* b */ 1", true), // '1 + 1' // lazyLast updated