Ticket #3281: t3281_highlighted_playername_almost_without_regex.patch

File t3281_highlighted_playername_almost_without_regex.patch, 1.9 KB (added by elexis, 9 years ago)

Replaces the RegExp with a function with less side effects. Still uses a RegExp to check if a single character is alphanumerical.

  • binaries/data/mods/public/gui/lobby/lobby.js

     
    828828    if (!msg.key)
    829829        msg.key = null;
    830830    if (!msg.datetime)
    831831        msg.datetime = null;
    832832
    833     // Highlight local user's nick
    834     if (msg.text.indexOf(g_Name) != -1 && g_Name != msg.from)
    835         msg.text = msg.text.replace(new RegExp('\\b' + '\\' + g_Name + '\\b', "g"), colorPlayerName(g_Name));
     833    if (g_Name != msg.from)
     834        msg.text = highlightPlayername(msg.text, g_Name);
    836835
    837836    // Run spam test if it's not a historical message
    838837    if (!msg.datetime)
    839838        updateSpamMonitor(msg.from);
    840839    if (isSpam(msg.text, msg.from))
     
    849848        g_ChatMessages.push(formatted);
    850849        Engine.GetGUIObjectByName("chatText").caption = g_ChatMessages.join("\n");
    851850    }
    852851}
    853852
     853// Replaces each occurance of the playername in the text with a highlighted / colored version
     854function highlightPlayername(txt, name)
     855{
     856    var leftIndex = -1, rightIndex = -1;
     857    var colored = colorPlayerName(name);
     858    while (rightIndex < txt.length)
     859    {
     860        leftIndex = txt.indexOf(name, rightIndex);
     861        rightIndex = leftIndex + name.length;
     862
     863        if (leftIndex == -1)
     864            break;
     865       
     866        // Left of the name must be non-alphanumerical character or no character at all
     867        if (leftIndex > 0 && txt.substr(leftIndex - 1, 1).match(/^[0-9a-z]$/))
     868            continue;
     869       
     870        // Right of the name must be non-alphanumerical character or no character at all
     871        if (rightIndex < txt.length && txt.substr(rightIndex, 1).match(/^[0-9a-z]$/))
     872            continue;
     873
     874        // Highlight local user's nick
     875        txt = txt.substr(0, leftIndex) + colored + txt.substr(leftIndex + name.length);
     876
     877        rightIndex = leftIndex + colored.length;
     878    };
     879    return txt;
     880}
     881
    854882function ircSplit(string)
    855883{
    856884    var idx = string.indexOf(' ');
    857885    if (idx != -1)
    858886        return [string.substr(1,idx-1), string.substr(idx+1)];