我正在尝试计算字符串中的所有字符,除了任何注释。 目标是能够在输入字段中写入我的所有代码,然后获取不包括所有注释的字符总数(“//”之后的整行)
这是我到目前为止得到的:
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/