jQuery-更改文本中字符串的颜色,而忽略< br>之间的 [英] JQuery - Change Color of String in a Text, ignoring <br>'s between
本文介绍了jQuery-更改文本中字符串的颜色,而忽略< br>之间的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要更改文本中特定子字符串的颜色. 文本如下所示:
I need to change the color of a specific sub-string in a text. The text looks like this:
SOME TE<br>
XT IS HER<br>
E.
我很讨厌jquery的.replace()
函数,它的问题是,如您在上面看到的,文本被那些<br>
分开了.我如何忽略"它们?
例如,我想用<span class="color-red">TEXT</span>
I tired the .replace()
function from jquery, the problem with it is, that, as you can see above, the text is splited with those <br>
's. How can I "ignore" them ?
For example I want to replace the String TEXT
with <span class="color-red">TEXT</span>
有人知道如何解决此问题吗?
Does anyone has an idea on how to solve this problem ?
推荐答案
无需jQuery.尽管我根本没有测试过,所以可能需要进行调整.
No jQuery required. Although I did not test this at all so it might need tweaking.
var customReplace = function(str, subStr, color) {
var words = str.split(' ');
for (var i = words.length - 1; i >= 0; i--) {
var word = words[i].replace(/<br>/g, '');
if (word === subStr) {
words[i] = '<span class="color-' + color + '">' + words[i] + '</span>';
}
}
return words.join('');
}
这篇关于jQuery-更改文本中字符串的颜色,而忽略< br>之间的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文