首页 > 解决方案 > 颜色特定文本

问题描述

我想在 HTML/PHP/CSS/JS 中有不同颜色的特定文本。

我有一个类似于这种结构的文本:

@john 请将邀请移至下周。

我想要实现的是将“@john”字样以绿色着色,而其余文本字符应保持黑色。换句话说,“@”和@之后的第一个空格“”是绿色文本的分隔符。

您能否就如何实现这一目标提出建议?

谢谢,苗条

标签: javascriptphphtmlcss

解决方案


您可以为此使用正则表达式;该字符\@将只匹配一个“@”,并且该字符\w+将匹配一个单词 - 一个单词是一组不被逗号、空格、句号等分隔的字符。

最后,您将需要使用 aString Iterator来查找所有匹配项并循环它们,当然,还要重新着色它们。

以下是您将如何执行此操作:

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."));


推荐阅读