javascript - 颜色特定文本
问题描述
我想在 HTML/PHP/CSS/JS 中有不同颜色的特定文本。
我有一个类似于这种结构的文本:
@john 请将邀请移至下周。
我想要实现的是将“@john”字样以绿色着色,而其余文本字符应保持黑色。换句话说,“@”和@之后的第一个空格“”是绿色文本的分隔符。
您能否就如何实现这一目标提出建议?
谢谢,苗条
解决方案
您可以为此使用正则表达式;该字符\@
将只匹配一个“@”,并且该字符\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."));
推荐阅读
- python - 一起使用 Snakemake 和 Dask 有意义吗?
- python - Python 3 urllib 库没有返回与 Chrome 上检查的相同的 HTML
- android - API < 23 上带有图像选择器的 MaterialButton
- linux - Web 中的 Vala Image Base64
- r - -title 中的错误:一元运算符的无效参数执行停止
- python - 如何使用正则表达式删除重复字符 Python
- python - selenium - 想要从表的第二列中选择所有值
- python - python拆分为n个数组(批处理)并尝试在一批数学中对相同的ID进行分组
- c - 如何排除非数字键?CS50 凯撒 Pset2
- python - Django如何添加有条件的类媒体