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.
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.
If the goal is smaller production files, your bundler or minifier can already strip comments:
{ format: { comments: false } } to minify() to drop all comments, including license comments it would otherwise keep.--minify removes comments; add --legal-comments=none to drop license comments too.comments: false option outputs code without comments, while keeping it readable.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.
For a one-off clean-up, paste your code into the Code Comment Remover:
//, /* */ and JSDoc comments// eslint-disable, // @ts-ignore and /*! license */ comments by defaultWorks for JavaScript and TypeScript, plus Python, Java and C/C++. 5 free tries, no account needed.
Open the Comment RemoverSome 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.