[英]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);
}
到目前為止,我的代碼計算了所有字符,包括//之后的行,但是循環有效,並且在所有“ //”之后都注銷了“找到”
謝謝你的幫助!
您可以通過刪除所有注釋然后計算字符數來實現。
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), "");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.