从列表中查找单词并将每个单词包装在一个跨度中? [英] Find words from a list and wrap each in a span?
问题描述
我想动态检查一个段落中的单词列表,然后在找到时将这些单词包装在 span 标签中.
I'd like to dynamically check a paragraph for a list of words and then wrap those words in a span tag if found.
示例:
<p class="para">
My house is red and my front door is blue.
</p>
我如何检查单词house"、red"、door"和blue",以及我可能添加到段落中的任何其他词,然后将它们包装在一个简单的跨度标签中,我然后可以用 css 样式吗?
How could I check for the words 'house', 'red', 'door', and 'blue', as well as any others I might add to the paragraph, and then wrap them in a simple span tag which I can then style with css?
我已经搜索并找到了单个单词的答案,但作为一个完整的新手,我不知道如何检查我可以添加到的列表.
I've searched and found answers for individual words, but being a complete novice I'm not sure how to check for a list of them which I can add to.
推荐答案
Javascript 有很棒的正则表达式 - 你可以使用它们.
Javascript has great regular expressions - you could use those.
var words = ['house', 'red', 'door', 'blue'];
// create a regular expression matching any of these words, using 'g' flag to match all instances
var regexp = new RegExp('(' + words.join('|') + ')', 'ig');
$('p.para').each(function(num, elem) {
var text = $(elem).text();
// use string.replace with $& notation to indicate whatever was matched
text = text.replace(regexp, '<span class="$&">$&</span>');
$(elem).html(text);
});
这会将您的所有单词放在一个具有匹配名称的跨度中,例如 house</span>
.您可以通过替换第一个$&"来为每个人设置相同的类带有一些预定义的类.
This will put all your words in a span with matching name, ex <span class="house">house</span>
. You could make it the same class for each one just by replacing the first '$&' with some predefined class.
这篇关于从列表中查找单词并将每个单词包装在一个跨度中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!