0

Hi I'm trying to remove all javascript comment (//) with in the HTML document. for example

<html>

<img src="http://example.com/img.jpg" />

<script>
//Some comments

gallery: {
      enabled: true,
      navigateByImgClick: true,
      preload: [0,1] // Will preload 0 - before current, and 1 after the current image
    },
</script>

</html>

Following is my regex code [^(http?s:)|ftp]\/\/(.*). This is working. But I want to make sure, Is there any way to improve this code. ?

5
  • Place your js inside own files (.js) and minify :) ? Commented Apr 8, 2014 at 8:17
  • What do you want to improve ? does it fail for some reasons ? Isn't it performant enough ? Also, I don't see the point... if that's important for you not to show the comments, you should really do this server-side, not client-side. Commented Apr 8, 2014 at 8:17
  • james.padolsey.com/javascript/… Commented Apr 8, 2014 at 8:19
  • 1
    That regex looks not only wrong for the task, but syntactically incorrect. Commented Apr 8, 2014 at 8:21
  • The fact that 50% of your regex is a special case for two scenarios gives it a really bad smell. What if the code had: console.log("this is a string with two slashes //"); What if some non-URL, non-JavaScript part of your HTML had two slashes somewhere? As Mauno V. said, if you want to remove the comments from your JS, then minify it. Commented Apr 8, 2014 at 8:21

1 Answer 1

1

Your regex says "match any character that isn't in fhpts?:(), followed by two literal slashes and anything to the ened of the line"

Normlly you'd want to do (?<!http)(?<!https)(?<!ftp)\/\/.*, however JavaScript doesn't support lookbehinds (much to everyone's disappointment) so consider doing this:

.replace(/\s\/\/.*/,"")

This will require comments to have a space before them (which they almost always do) - it's not perfect, but it's the best I can think of right now XD

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

Comments

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.