JavaScript October 29, 2026 · 5 min read

How to Remove Comments from JavaScript Code

JavaScript has two comment styles, string literals in three flavours and regex literals that can contain slashes — which is why removing comments is trickier than it looks. Here are the approaches that work.

The regex trap

A quick search turns up patterns like this:

const cleaned = source.replace(/\/\/.*|\/\*[\s\S]*?\*\//g, "");

It works on simple files, then breaks on perfectly normal code:

const api = "https://example.com/api";   // the URL is cut at //
const re = /https?:\/\//;                // a regex literal containing //
const tpl = `/* not a comment */`;        // comment syntax inside a template

To remove comments safely you need something that understands JavaScript's strings, template literals and regex literals — a parser or a tokenizer.

Option 1: Let your build tool do it

If the goal is smaller production files, your bundler or minifier can already strip comments:

Note: minifiers also rename variables and compress your code. That's right for build output, but not for source files you'll keep editing.

Option 2: A comment-stripping package

Small packages such as strip-comments on npm remove comments without minifying. Check how they handle regex literals and template strings before running them over a whole codebase.

Option 3: A free online tool

For a one-off clean-up, paste your code into the Code Comment Remover:

Strip JavaScript comments in one click

Works for JavaScript and TypeScript, plus Python, Java and C/C++. 5 free tries, no account needed.

Open the Comment Remover

Keep the comments that matter

Some comments change how your tools behave. Removing // eslint-disable-next-line brings lint errors back, and // @ts-expect-error is checked by TypeScript. License headers may be required when you redistribute code. Strip everything else freely.

If you're cleaning up AI-generated JavaScript, you may want to remove only the comments that repeat the code, and keep the ones that explain decisions. That's what the Code Humanizer does.

Summary