JAVASCRIPT

Remove C-style Multi-line Comments

Learn to strip multi-line `/* ... */` comments from code or configuration files using a regular expression, useful for minification or processing.

const codeWithComments = `function add(a, b) {
  /* This is a
   * multi-line comment
   */
  const sum = a + b; // This is a single-line comment (not targeted)
  /* Another block comment */
  return sum;
}`;

const removeMultiLineCommentsPattern = /\/\*[\s\S]*?\*\//g;

const cleanedCode = codeWithComments.replace(removeMultiLineCommentsPattern, '');

console.log(cleanedCode);
/* Expected Output:
function add(a, b) {
  
  const sum = a + b; // This is a single-line comment (not targeted)
  
  return sum;
}*/
How it works: This regex pattern is designed to remove C-style multi-line comments (`/* ... */`) from text. `/\*` matches the opening delimiter, `[\s\S]*?` non-greedily matches any character (including newlines) zero or more times, and `\*\/` matches the closing delimiter. The `g` flag ensures all occurrences are removed, making it useful for code minification or stripping comments from configuration files.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs