Javascript 避免在代码中计算注释

Javascript 避免在代码中计算注释,javascript,for-loop,while-loop,comments,Javascript,For Loop,While Loop,Comments,我试图计算字符串中的所有字符,除了任何注释。 目标是能够在输入字段中写入我的所有代码,然后获得不包括所有注释的字符总数(在“/”后面的整行) 到目前为止,我得到的是: function findComments() { var string = document.getElementById("input").innerText; var splittedString = string.split(""); var totalComments = ""; var

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

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

 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);
}
函数findComments(){
var string=document.getElementById(“输入”).innerText;
var splittedString=string.split(“”);
var totalComments=“”;
var count=“”;
对于(var i=0;i
到目前为止,我的代码统计所有字符,包括//之后的行,但循环有效,它在所有“/”之后注销“find”


谢谢你的帮助

您可以删除所有注释,然后计算字符数

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

你能描述一下你的目标和更多的内容吗?目标是将大量代码复制到一个输入字段中,然后在不计算注释的情况下计数所有字符,而不考虑诸如“代码> var字符串=“某些/ /文本”之类的东西;代码>您将需要一个状态机。字符串文本将来自输入字段“input”算法:尝试删除从“//”到“\n”范围内的所有字符。然后只需计算已处理字符串中的字符数