3

我正在尝试为我的网站创建一个文本突出显示选项。但是我想要精确的单词匹配而不是模糊的单词匹配,我拥有的代码匹配所有类型的实例并且它有一些区分大小写的问题。如果我们以 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));
});
4

1 回答 1

2

您需要利用正则表达式的Word Boundaries

更改以下行:

var entityRegularExpression = new RegExp(entityText, "g");

对此:

var entityRegularExpression = new RegExp("\\b" + entityText + "\\b", "gi");

这是更新的jsfiddle。
注意:我更新了文章文本以包含该单词的一些实例,以便您可以看到它有效。

您还可以更进一步,通过使用正则表达式的Callbacks让不区分大小写的匹配项保留其原始大小写。查看此 jsfiddle以获取代码和示例。

于 2012-06-13T06:27:23.617 回答