test_get_all_console.js
let fs = require("fs")
let re = /console\.\w+\(.*\)/
let str = fs.readFileSync("./1.js", "utf-8")
// let str2 = str.replace(re, "")
// console.log("222->", str2)
// 找到字符串的结尾 根据给定的 " ' ` 返回该字符串, 和其长度
function find_str_end_by_start(tip, x, arr) {
let str = "", length = 0, flag = false;
while (!flag) {
x++
length++
str += arr[x]
if (arr[x] == tip && arr[x - 1] != `\\`) {
flag = true
}
}
return {
length,
str
}
}
function my_replace_console(str) {
let o_str = str
let arr = str.split("")
let need_replace_arr = [] // 需要去掉的打印信息
for (let i = 0; i < arr.length; i++) {
if (
arr[i].toLocaleLowerCase() == "c" &&
arr[i + 1].toLocaleLowerCase() == "o" &&
arr[i + 2].toLocaleLowerCase() == "n" &&
arr[i + 3].toLocaleLowerCase() == "s" &&
arr[i + 4].toLocaleLowerCase() == "o" &&
arr[i + 5].toLocaleLowerCase() == "l" &&
arr[i + 6].toLocaleLowerCase() == "e" &&
arr[i + 7].toLocaleLowerCase() == "."
) {
let item_need_replace = "console."; // 当前需要去掉的打印信息
// 找第一个括号 之后找第二个括号
// 若遇到字符串 则先找到字符串的结尾 期间遇到的所有括号和转义过的
let x = i + 7
let flag = false
let flag_kuohao = true // 括号是完美的(即没有括号或者括号是成对的)
let kuohao_L = []
// while(!arr[x] == ")") {
while (!flag) {
x += 1
item_need_replace += arr[x]
// console.log("当前字符串是 item_need_replace", item_need_replace)
if (arr[x] == '"') {
let obj = {}
obj = find_str_end_by_start('"', x, arr)
item_need_replace += obj.str
x += obj.length
} else if (arr[x] == "'") {
let obj = {}
obj = find_str_end_by_start("'", x, arr)
item_need_replace += obj.str
x += obj.length
} else if (arr[x] == "`") {
let obj = {}
obj = find_str_end_by_start("`", x, arr)
item_need_replace += obj.str
x += obj.length
} else if (arr[x] == "(") {
kuohao_L.push("(")
flag_kuohao = false
} else if (arr[x] == ")") {
kuohao_L.pop(")")
if (kuohao_L.length == 0) {
flag_kuohao = true
}
}
if (arr[x] == ')' && flag_kuohao) {
flag = true
}
}
let flag2 = false;
while (!flag2) {
x += 1
console.log("x--->", x)
let aaa = arr[x]
console.log("arr[x]--->", aaa)
item_need_replace += arr[x]
if (arr[x] == ';' || (arr[x] == '\r' && arr[x + 1] == '\n')) {
flag2 = true
}
}
need_replace_arr.push(item_need_replace)
}
}
console.log("arr ~ need_replace_arr", need_replace_arr)
need_replace_arr.map(it => {
o_str = o_str.replace(it, "")
})
return o_str
}
let res = my_replace_console(str)
console.log(" res----->", res)
1.js 测试文件
let aaa = 123;
console.log(123, "()123123aaa\r\nasaszzz")
console.warn(7777, "aaaaa<>sa?dASd/?d/as()123123aaa\r\nasaszzz"); // 123
console.log(`
asd
127389()
""
''
`)
console.log()
console.log(777)
console.log(fun()
)