1

I am aware of this: Regex to remove comments from SQL Query String using JavaScript

Which I thought as the answer, but that still leaves the newline which I also need to remove:

sql = `HELLO 1
-- comments 1
HELLO 2
-- comments 2
HELLO3
`;

sql.replace(/.*--.*/g,'');

But this still leaves spaces and does not remove the whole line:

HELLO 1

HELLO 2

HELLO3

What I am looking for is this:

HELLO 1
HELLO 2
HELLO3

How can I achieve this in the regex without executing a second replace to replace blank lines ?

crankshaft
  • 2,607
  • 4
  • 45
  • 77
  • Try this `\n.*--.*` – Alireza Nov 11 '20 at 09:46
  • 1
    Append ```\r?\n|\r``` to your regex to remove newlines ... have a look here: https://stackoverflow.com/questions/10805125/how-to-remove-all-line-breaks-from-a-string – Mischa Nov 11 '20 at 09:48
  • Thanks, but cannot remove newlines as they might be valid, the regex need to match the line starting with -- and remove it – crankshaft Nov 11 '20 at 09:50

1 Answers1

0

Maybe this can help you:

\n(\/\*[^*]*\*\/)|(\/\/[^*]*)|\n(--[^.].*)

See Demo

Code:

sql = `HELLO 1
-- comments 1
HELLO 2
-- comments 2
HELLO3
`;

sql.replace(/\n(\/\*[^*]*\*\/)|(\/\/[^*]*)|\n(--[^.].*)/g,'');
Alireza
  • 2,103
  • 1
  • 6
  • 19