【问题标题】:Color specific text颜色特定文本
【发布时间】:2021-06-19 10:42:34
【问题描述】:

我希望在 HTML/PHP/CSS/JS 中使用不同颜色的特定文本。

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

@john 请将邀请移至下周。

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

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

谢谢, 修身

【问题讨论】:

  • 您想使用JS
  • 您自己尝试过什么吗?如果是这样,请发布您的代码的简要摘要。
  • 嗨@AlphaHowl - 我试图将 color:green 属性添加到表格中,从那里将文本放入 UI。但是这种解决方法不起作用。
  • @AlphaHowl - 是的,我更喜欢 JS 中的东西。
  • 好的,等等……

标签: javascript php html css


【解决方案1】:

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

最后,您需要使用String 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."));

【讨论】:

  • 没问题 :) ,
猜你喜欢
  • 2015-10-10
  • 2016-02-02
  • 2018-04-29
  • 2013-04-17
  • 2013-05-12
  • 2012-03-19
  • 1970-01-01
  • 2012-03-13
  • 2017-12-31
相关资源
最近更新 更多