Home > Blockchain >  I need advice on code to change the color of certain words throughout a sentence
I need advice on code to change the color of certain words throughout a sentence

Time:12-11

I wrote a code that allows you to view the triggered alarms on the web in order to see the network logs more comfortably, and confirmed that some code that changes the color of the entire code works very inefficiently.

However, I'm lacking in JavaScript knowledge, so I'm out of ideas on how I can get that code to work efficiently.

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)
            }
        }
    }
}

It works the way I want, but this code seems pretty problematic.

CodePudding user response:

You don't need 3 loops, nor do you need 3 regex method calls.

A single call to replace can do everything for you. You can also use "magic patterns" like $& inside the second argument of replace, so you don't even need a function there.

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

  • Related