create a regex expression that ignores comments in javascript

To create a regular expression that ignores comments in JavaScript, we can use the following pattern:

index.tsx
/(\/\/[^\n]*|\/\*[\s\S]*?\*\/)/g
33 chars
2 lines

This regular expression pattern matches both single-line and multi-line comments in JavaScript code. Here is how the pattern works:

  • \/\/[^\n]* matches single-line comments that start with // and continue until the end of the line.
  • \/\*[\s\S]*?\*\/ matches multi-line comments that start with /* and end with */.

The [\s\S]*? part of the pattern matches any character (including line breaks) in a non-greedy way, so it stops matching at the first occurrence of */.

The g flag at the end of the pattern enables global matching, which means the regular expression pattern will match all occurrences of comments in the input string.

Here's an example of how to use this regular expression to remove comments from JavaScript code:

index.tsx
const codeWithComments = `
// This is a single-line comment
console.log("Hello!"); // Another single-line comment
 
/* This is a
   multi-line comment */
let x = 10; /* Another
              multi-line comment */
`;
 
const codeWithoutComments = codeWithComments.replace(/(\/\/[^\n]*|\/\*[\s\S]*?\*\/)/g, '');
console.log(codeWithoutComments);
// Output: 
// 
// console.log("Hello!"); 
// 
// 
// let x = 10; 
411 chars
19 lines

gistlibby LogSnag