繁体   English   中英

我需要有关代码的建议以更改整个句子中某些单词的颜色

[英]I need advice on code to change the color of certain words throughout a sentence

我写了一段代码,可以让你查看 web 上触发的警报,以便更舒适地查看 .network 日志,并确认某些更改整个代码颜色的代码工作效率非常低。

但是,我缺乏 JavaScript 知识,所以我不知道如何让该代码有效地工作。

const color_set = {
    'red': ['vrrp', 'ospf', 'hop router', 'stp', 'hsrp', 'bgp', 'updown', /\bup.\b/, /\bdown\b/],
    'green': ['enable', 'allow', 'enabled'],
    'yellow': ['cannot', 'alert'],
    'blue': ['notice'],
    'violet': [/\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/g]

};


var alert_log = "Nov 10 02:14:50 SUN OSPF: nbr state changed, rid 192.160.10.40, nbr addr 172.16.10.2, nbr rid 192.168.10.10, state down"


for (let color of Object.keys(color_set)){
    for (const item of color_set[color]){
        let p = new RegExp(item, 'gi')
        if (p.test(alert_log) == 1){
            let tmp = alert_log.match(p)
            let j = 0

            for (let matchText of tmp){
                let i = 0
                ++j
                alert_log = alert_log.replace(p, match => ++i == j ? `<span style="color: ${color};">${matchText}</span>` : match)
            }
        }
    }
}

它按我想要的方式工作,但这段代码似乎有问题。

您不需要 3 个循环,也不需要 3 个正则表达式方法调用。

一次调用replace即可为您完成一切。 您还可以在replace的第二个参数中使用$&之类的“魔术模式” ,因此您甚至不需要 function 。

 const color_set = { 'red': ['vrrp', 'ospf', 'hop router', 'stp', 'hsrp', 'bgp', 'updown', /\bup.\b/, /\bdown\b/], 'green': ['enable', 'allow', 'enabled'], 'yellow': ['cannot', 'alert'], 'blue': ['notice'], 'violet': [/\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/g] }; var alert_log = "Nov 10 02:14:50 SUN OSPF: nbr state changed, rid 192.160.10.40, nbr addr 172.16.10.2, nbr rid 192.168.10.10, state down" for (let color of Object.keys(color_set)){ for (const item of color_set[color]){ const p = new RegExp(item, 'gi') alert_log = alert_log.replace(p, `<span style="color: ${color};">$&</span>`) } } //Just to display the colored string: document.body.innerHTML = alert_log

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM