Skip to content
Advertisement

Color specific text

I would like to have a specific text colored differently in HTML/PHP/CSS/JS.

I have a text similar to this structure:

@john please move the invite to the next week.

What i would like to achieve is to have the wording “@john” colored in green while the rest of the text characters should remain in black. In other words the “@” and the first space ” ” right after the @, are the delimiters of the green text.

Can you please advise on how to achieve this?

Thanks, Slim

Advertisement

Answer

You can use Regular expressions for this; the character @ will just match a “@”, and the character w+ will match a word – a word is a set of characters which are unseparated by commas, spaces, full stops, etc.

Lastly, you will need to use a String Iterator to find all matches and loop through them, and, of course, re-color them.

Here is how you would do this:

function color_text(text) {
    let matches = text.matchAll(/@w+/g);
    let current_match;
    while(!current_match?.done) {
        current_match = matches.next();
        if(current_match?.done) {
            break;
        }
        let value = current_match?.value[0];
        text = text.replace(value, "<span style='color: #00db58'>" + value + "</span>");
    }
    return text;
}


// TESTING HERE  -- - - -- - - -

document.write(color_text("@john please move the invite to the next week."));
document.write("<br>");
document.write(color_text("@john please tell @josh to stop being annoying."));
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement