1

I managed to find the regex for handling /* */ cases but it doesn't work well for -- cases. How can I change my regex to fix this?

var s = `SELECT * FROM TABLE_A
/* first line of comment
   second line of comment */
   -- remove this comment too
   SELECT * FROM TABLE_B`;

var stringWithoutComments = s.replace(/(\/\*[^*]*\*\/)|(\/\/[^*]*)|(--[^*]*)/g, '');
/*
Expected:

SELECT * FROM TABLE_A
SELECT * FROM TABLE_B
*/
console.log(stringWithoutComments);

Thank you

https://jsfiddle.net/8fuz7sxd/1/

4
  • And what about a comment appearing inside a string literal? And other edge cases. You should really use an SQL parser for this, skip all the comments and then write back the resulting SQL. And what about OR/* comment */DER? Commented Sep 6, 2019 at 0:20
  • 2
    Remember: whenever you ask for a regex, a regex is usually not the correct solution. Commented Sep 6, 2019 at 0:21
  • @RolandIllig What would be the better potential solution? Commented Sep 6, 2019 at 0:30
  • As I said: use a proper SQL parser Commented Sep 6, 2019 at 21:27

1 Answer 1

5

var s = `SELECT * FROM TABLE_A
/* first line of comment
   second line of comment */
   -- remove this comment too
   SELECT * FROM TABLE_B`;

var stringWithoutComments = s.replace(/(\/\*[^*]*\*\/)|(\/\/[^*]*)|(--[^.].*)/gm, '');
/*
Expected:

SELECT * FROM TABLE_A
SELECT * FROM TABLE_B
*/
console.log(stringWithoutComments);

// without linebreak
stringWithoutComments = stringWithoutComments.replace(/^\s*\n/gm, "")
console.log(stringWithoutComments);


// without whitespace
stringWithoutComments = stringWithoutComments.replace(/^\s+/gm, "")
console.log(stringWithoutComments);

Sign up to request clarification or add additional context in comments.

2 Comments

This does not work if the comment contains "*" in it.
This will break when /* or -- appear in strings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.