javascript - 避免计算代码中的注释

标签 javascript for-loop while-loop comments

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

这是我到目前为止得到的:

 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), "");
    }
}

关于javascript - 避免计算代码中的注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48078318/

相关文章:

javascript - 包含用户添加的行以及每行上的输入元素查找的表单

python - l.append[i],对象不可下标?

javascript - 理解 javascript 中的 for 循环

c - While循环第二次忽略scanf

Javascript 相等怪异

javascript - JQuery 在正文单击时隐藏上下文菜单

javascript - 从数据库插入下拉列表到wordpress页面($.post没有功能)

c - 循环结构: FOR in C

while-loop - while (true) 与break 是不好的编程习惯吗?

c - 再次打印对函数的最后一次调用