#Recolor text case-insensitively

1 messages · Page 1 of 1 (latest)

solar sun
#

This function will recolor any matching term in a string (case insensitive). Useful for things like displaying terms that match a search.

recolor(text, term, colorCode = '§f') {
    const lowerText = text.toLowerCase();
    const lowerTerm = term.toLowerCase();
    const index = lowerText.indexOf(lowerTerm);
    if (index === -1) return text;
    const splitText = lowerText.split(lowerTerm);
    let newText = '';
    let lastColorCode = '';
    let currentIndex = 0;

    for (let i = 0; i < splitText.length; i++) {
        let splice = splitText[i];
        let originalSplice = text.slice(currentIndex, currentIndex + splice.length);
        currentIndex += splice.length;

        if (i === splitText.length - 1) {
            newText += originalSplice;
            continue;
        }

        let colorCodeIndex = originalSplice.lastIndexOf('§');
        if (colorCodeIndex === -1) {
            newText += originalSplice + colorCode + text.slice(currentIndex, currentIndex + term.length) + lastColorCode;
        } else {
            lastColorCode = originalSplice.slice(colorCodeIndex, colorCodeIndex + 2);
            newText += originalSplice + colorCode + text.slice(currentIndex, currentIndex + term.length) + lastColorCode;
        }

        currentIndex += term.length;
    }

    return newText;
}

Example:

thorn tartan
safe dragon
#

text.replaceAll( /help|spawn|tp/g, "§e$&§f" )

solar sun
#

@safe dragon this is not the same thing. relpaceAll does not take into account the color of the text prior to the replacement. (also the regex should be one word case insensitively to match)

neat herald
#
const recolor = (text, terms, colorCode = '§f', resetCode = '§f') => {
    const regex = new RegExp(`(${terms.join('|')})`, 'gi');
    return text.replace(regex, (match) => `${colorCode}${match}${resetCode}`);
};

const text = "Use help to get spawn coordinates or tp to the location.";
const terms = ['help', 'spawn', 'tp'];
const coloredText = recolor(text, terms, '§e');
console.log(coloredText);
solar sun
#

Still a hardcoded resetCode haha

#

Btw Im almost certain someone can do this better with both the case insensitivity and the dynamic color reset, so I leave that up to you all