我正在尝试为我的网站创建一个文本突出显示选项。但是我想要精确的单词匹配而不是模糊的单词匹配,我拥有的代码匹配所有类型的实例并且它有一些区分大小写的问题。如果我们以 Jfiddle 为例,我只想添加单词cancer,区分大小写应该不是问题。并忽略模糊匹配,如癌性和癌性(我知道没有这样的词,但想不出任何例子)。我有 jfiddle 链接 http://jsfiddle.net/ehzPQ/6/
HTML:
<div id="entity">cancer</div>
<div id="article">
This kind of insurance is meant to supplement health insurance for cancerous-care costs. But generally you're better off putting your money toward comprehensive health policies. The I just repeat health insurance, because it sounds so good! health insurance, health insurance, I can never grow tired of it... Cancer is seriously a dangerouse disease. Test case : bycanceraous
</div>
CSS:
.highlight {
background-color: yellow
}
Javascript:
$(document).ready(function(){
var $test = $('#article');
var entityText = $('#entity').html();
var entityRegularExpression = new RegExp(entityText,"g");
var highlight = '<span class="highlight">' + entityText + '</span>';
$test.html($test.html().replace(entityRegularExpression, highlight));
});