JavaScript / ECMAScript

Single-Line Comment (// or #) in JS

Match single-line comments using either the `//` (C-family) or `#` (shell, Python, Ruby, YAML) marker.

Try it in the JS tester →

Pattern

regexJS
(?://|#).*$   (flags: gm)

JavaScript / ECMAScript code

jsJavaScript
const re = new RegExp("(?://|#).*$", "gm");
const input = "var x = 1; // assignment\\n# python style\\ny = 2";
const matches = [...input.matchAll(re)];
console.log(matches.map(m => m[0]));

Uses `String.prototype.matchAll` for global iteration (Node 12+ / all modern browsers).

How the pattern works

(?://|#) is a non-capturing group matching either marker. .*$ matches the rest of the line up to the newline. The g flag finds every comment; the m flag makes $ anchor at line boundaries instead of just end-of-string.

Examples

Input

var x = 1; // assignment\n# python style\ny = 2

Matches

  • // assignment
  • # python style

Input

Just a // sample line

Matches

  • // sample line

Input

no comments here

No match

Same pattern, other engines

← Back to Single-Line Comment (// or #) overview (all engines)