Skip to content

Regex for Javascript Comment — Pattern, Examples & Caveats

Pattern flags: gm
\/\/.*$|\/\*[\s\S]*?\*\/

This pattern matches both JavaScript comment styles: single-line // comments to end of line, and block /* */ comments spanning any characters lazily. It is used to strip or locate comments in JS source. Web patterns deal with markup, styling and web identifiers: HTML tags and comments, CSS colors, Markdown links, slugs and source-code comments. They are handy for quick scanning and lightweight transforms, but markup is not a regular language, so anything structural or security-sensitive should use a real parser (DOM, CSS or Markdown) rather than regex alone. It uses the gm flag(s). Apply it across text to collect every occurrence. It will match // inside strings or URLs (like http://) as a false positive — stripping comments with regex can corrupt code; use a tokenizer for safety. Block comments do not nest in JavaScript, and the lazy match handles the common case but not malformed input. Regex-based comment removal is risky for real code transformation; prefer a parser like Babel or Acorn. As with any regular expression, confirm its behavior in your target engine, test boundary and adversarial inputs, and watch for catastrophic backtracking before relying on it in production.

Advertisement
Ad slot · ref-top

Token-by-token explanation

  • \/\/.*$ — a // comment through the end of the line
  • | — alternation between the two comment forms
  • \/\*[\s\S]*?\*\/ — a /* ... */ block, lazy across newlines
  • g flag — find all comments
  • m flag — so $ matches each line end for // comments

What it matches

// note/* block *//* multi line */code(); // trailing

What it does not match

http://example.com/* unclosednot a comment

When to use it

Reach for a web pattern for quick scanning and lightweight transforms of markup, styling and web identifiers: locating tags, comments, colors, slugs or Markdown links. For anything structural or security-sensitive — parsing a DOM, sanitizing HTML, rewriting CSS — use a real parser or a proven library instead, because markup is not a regular language and regex-based handling is a frequent source of bugs and cross-site scripting bypasses.

Caveats

  • It will match // inside strings or URLs (like http://) as a false positive — stripping comments with regex can corrupt code; use a tokenizer for safety.
  • Block comments do not nest in JavaScript, and the lazy match handles the common case but not malformed input.
  • Regex-based comment removal is risky for real code transformation; prefer a parser like Babel or Acorn.

Code examples

JavaScript
const re = /\\/\\/.*$|\\/\*[\s\S]*?\*\\//gm;
const text = "see // note and more";
const found = [...text.matchAll(re)].map(m => m[1] ?? m[0]);
// found holds every extracted occurrence
Python
import re

rx = re.compile(r"\/\/.*$|\/\*[\s\S]*?\*\/", re.M)
text = "see // note and more"
found = rx.findall(text)   # every occurrence (groups if present)
Java
import java.util.regex.*;

Pattern p = Pattern.compile("\\/\\/.*$|\\/\\*[\\s\\S]*?\\*\\/", Pattern.MULTILINE);
Matcher m = p.matcher("// note");
boolean ok = m.find();   // scan for occurrences
PHP
<?php
$subject = "// note";
if (preg_match_all('/\\/\\/.*$|\\/\*[\s\S]*?\*\\//m', $subject, $m)) {
    // $m[0] is the full match; $m holds every occurrence
}

How to test it

Before trusting any pattern, test it against three kinds of input: valid examples that must match, invalid examples that must be rejected, and edge cases at the boundaries (empty strings, maximum lengths, unusual separators and Unicode). Paste the expression into a live regex tester with your actual sample data and confirm the highlighted matches are exactly what you intend. Watch for catastrophic backtracking by trying long non-matching inputs, and remember that engine differences (JavaScript, Python, Java, PCRE, Go/RE2) mean a pattern that works in one may fail or behave differently in another — especially lookarounds, which Go's RE2 does not support at all.

Frequently asked questions

Why does it match http:// in a string?

Because the regex has no awareness of string literals, so the // in a URL looks like a comment. This is why comment stripping should use a real tokenizer, not regex, for production code.

Can it handle nested block comments?

JavaScript block comments do not nest, so /* a /* b */ ends at the first */. The lazy pattern matches that correctly, but nested-looking input is simply invalid JS.

When should I avoid regex for web content?

For parsing HTML, CSS or Markdown structure, use a real parser. Regex cannot handle nesting, quoted delimiters or malformed markup reliably, and regex-based sanitization is a common source of XSS bypasses.

Why is regex HTML sanitization dangerous?

HTML has nested, quoted and malformed constructs that regex mis-parses, so attackers hide scripts in forms the pattern misses. Always sanitize with a proven library (DOMPurify) or a real parser, never ad-hoc regex.

Advertisement
Ad slot · ref-in-article

Try the Regex Tester

Live regex matching with groups, flags and explanations.

Open tool →