0

I'm trying to reliably strip out Javascript multi-line and single-line comments in Java or Scala. Even if it requires running an external program, that would be OK (but not ideal). There must be some library or tool to do this. I've looked at this post:

http://james.padolsey.com/javascript/removing-comments-in-javascript/

and converted it to Scala. But his logic is broken in a few different ways. One problem is that it doesn't properly tell the difference between division and the start of a regex. It also doesn't handle escape sequences in all situations. I've been trying to fix this code, but its tricky - especially telling the difference between regex and division.

I don't want to re-invent the wheel here, and I don't want to build a freaking Javascript parser. Any ideas?

6
  • sample input and output would be helpful Commented Sep 8, 2014 at 16:06
  • You have two comment cases, i.e., // for single-line and /*...*/ for multi-line, right? Using a sub-string search function for these three specific patterns may be your best bet... Commented Sep 8, 2014 at 16:07
  • Not sure what you mean by input and output. Input would be any possible Javascript. Output would be that same text, but with all comments removed... Commented Sep 8, 2014 at 16:07
  • 1
    @abiessu, I think that over-simplifies things because you could be inside of a string or a regex literal Commented Sep 8, 2014 at 16:08
  • Have you considered using a Regex strip that would move something along the lines of /** etc etc**/ and // etc etc \n Commented Sep 8, 2014 at 16:10

1 Answer 1

2

I think there should be a tool to help you with that but as another option you can use a regex like this:

//.*|/\*[\S\s]+?\*/

Working demo

enter image description here

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

1 Comment

What if there is a line like this in the code?: console.log('Comments in javascript are denoted by //comment text here')

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.