如果文本包含'@'更改'@'的颜色 [英] if text contains '@' change color of '@'
问题描述
我在寻找解决我的问题的解决方案。
我有一个段落,有一些twitter tweet的文字。现在我想将所有的'@'改为一种颜色。
I'm looking for a solution for my problem.
I have a paragraph with some text from a twitter tweet. Now I would like to change all the '@'s to a color.
这是我在我的文本中查找'@'的方法:
This is what I do to look for '@'s in my text:
if (status.indexOf("@") >= 0)
{
}
但现在如何改变@的颜色? (添加范围和类或某事...)
But now how can I change the color of the @? (Add a span and class or something ...)
状态是一个变量,内容为ex。像这样:
The status is a variable with content for ex. like this:
Dita Von Teese draagt geprinte 3D-jurk <a target="_blank" href="http://t.co/s2y6b21S0I">http://t.co/s2y6b21S0I</a> via @<a target="_blank" href="http://twitter.com/Knackweekend">Knackweekend</a>
推荐答案
没有看到你的HTML,一个简单的替换,我假设 status
是HTML元素/节点的jQuery集合:
Without seeing your HTML, the best I can offer is a simple replace, and I'm assuming that status
is a jQuery collection of HTML elements/nodes:
status.html(function(i,h){
return h.replace(/@/g,'<span class="atSign">@</span>');
});
与CSS结合:
.atSign {
color: #f90;
}
更新,因为状态
看起来是一个字符串(来自下面的注释):
Updated, since status
appears to be a string (from the comments, below):
var status = '<a target="_blank" href="t.co/s2y6b21S0I">http://t.co/s2y6b21S0I</a>; via @<a target="_blank" href="twitter.com/Knackweekend">Knackweekend</a>',
newStatus = status.replace(/@/g,'<span class="atSign">@</span>');
console.log(newStatus);
要使 @
/ em>以下 a
元素:
.atSign,
.atSign + a {
color: #f90;
}
包装 @
span
:
var status = '<a target="_blank" href="t.co/s2y6b21S0I">http://t.co/s2y6b21S0I</a>; via @<a target="_blank" href="twitter.com/Knackweekend">Knackweekend</a>',
newStatus = status.replace(/(@.+<\/a>)/g,function(a){
return '<span class="atSign">' + a + '</span>';
});
console.log(newStatus);
参考资料:
html()
.- JavaScript regular expressions.
String.replace()
.
这篇关于如果文本包含'@'更改'@'的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!