避免计算代码中的注释

Avoid counting comments in code

我正在尝试计算字符串中的所有字符,但任何注释除外。 目标是能够在输入字段中写入我的所有代码,然后获得不包括所有注释的字符总数(“//”之后的整行)

这是我目前得到的:

 function findComments() {
    var string = document.getElementById("input").innerText;
    var splittedString = string.split("");
    var totalComments = "";
    var count = "";
    for (var i = 0; i < splittedString.length; i++) {
        if (splittedString[i]+splittedString[i+1] == "//") {
           console.log("found");
        } else {
            count++;
        }
    }
    console.log(count);
}

到目前为止,我的代码计算了所有字符,包括 // 之后的行,但是循环有效并且它在所有“//”

之后注销 "found"

感谢您的帮助!

您可以通过删除所有评论然后计算字符数来完成。

function main() {
    var code = "var x = 0; // this is comment \n print(x)\n";

    var result = removeComments(code)
    console.log(result)
    // Result: var x = 0; \n print(x)\n
    console.log(result.length)
    // Result: 20
}
function removeComments(code) {
    var result = code
    while (true) {
       var commentIndex = result.indexOf("//");
       var endOfStringIndex = result.indexOf("\n");
       // return from function if no // or \n found in code
       if (commentIndex == -1 || endOfStringIndex == -1) { return result; }
       result = result.replace(result.substring(commentIndex, endOfStringIndex+2), "");
    }
}