JavaScript的文字颜色更改为每个单词阵列 [英] JavaScript Text Color Change To Each Word In Array
本文介绍了JavaScript的文字颜色更改为每个单词阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个JavaScript的code:
I have this JavaScript Code:
$(function() {
var text = $(this).find("#text").html();
var key_words = ['university', 'students', 'institutions', 'education'];
function colorText(text, keywords) {
var rd;
$.each(keywords, function(index, item) {
var r = new RegExp(item, "gi")
rd = text.replace(r, '<span style="background: yellow">' + item + '</span>');
});
return rd;
}
var colorWords = colorText(text, key_words);
$(this).find("#text").html(colorWords);
});
我要全部更换key_words阵列颜色简单和容易。但总是在彩色全文只有学生和多数民众赞成。
I want to replace all key_words array with colors simple and easy. But always colored only students in whole text and thats all.
我是什么,我做错了。先谢谢了。
What i'm i doing wrong. Thanks in advance.
推荐答案
这样做没有一个循环的另一种方式,应该是:
Another way of doing it without a loop, would be:
function colorText(text, keywords) {
var regex = new RegExp(keywords.join('|'), 'gi');
return text.replace(regex, '<span style="background: yellow">$&</span>');
}
这篇关于JavaScript的文字颜色更改为每个单词阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文