1

I'm working on a code that allows the user to check his/her code for a total number of chars, without counting any comment ( // and /* )

So far, it's counting correct on every // and also on /* except, it will start counting in the next line after /*, and it should wait until it receives a */ (end of comments).

function findComments() {
        
  var string = document.getElementById("input").value;
  var splittedString = string.split("\n");
      
  var count = 0;
      
  for (var i = 0; i < splittedString.length; i++) {
          
    if(splittedString[i].indexOf("//") === -1 && 
       splittedString[i].indexOf("/*") === -1) {
        
      var chars = splittedString[i].split("");
      for (var j = 0; j < chars.length; j++) {
        count++;
      }
    }
  }
  console.log(count);
}
<button onclick="findComments()">Find Comments</button>
<textarea rows="10" cols="40" id="input"></textarea>
theAlexandrian
  • 870
  • 6
  • 18
ITGuru
  • 115
  • 1
  • 12
  • 1
    You're just ignoring lines that have /* in them - you're not ignoring any lines following. You could set a flag to true to tell it to ignore lines, and then reset it to false when you find a **/, but honestly this is a very messy thing to do. What about characters on a line before // or /* or on a line after */? – Reinstate Monica Cellio Jan 03 '18 at 16:20
  • I understand what ur point is, but what do u mean with 'flag'? some kind of boolean set to true? My problem is that i split every time there is a new line, and i loop through this. I cant continue the loops until i reach a */ which would be smart, because then it wont go into the if statement again. – ITGuru Jan 03 '18 at 16:22
  • 1
    This is what you should be looking at... https://stackoverflow.com/questions/5989315/regex-for-match-replacing-javascript-comments-both-multiline-and-inline (I'm not voting to close as I don't consider it a duplicate question). – Reinstate Monica Cellio Jan 03 '18 at 16:36

0 Answers0