我正在尝试为我的网站创建一个文本突出显示选项。但我想要精确的单词匹配而不是模糊的单词匹配,我的代码匹配所有类型的实例,并且存在一些区分大小写的问题。如果我们以 Jfiddle 为例,我只想添加这个词cancer,区分大小写不应该成为问题。并忽略模糊匹配,例如 cancerous 和 bycanceraous(我知道没有这样的词,但想不出任何例子)。我有 jfiddle 链接http://jsfiddle.net/ehzPQ/6/ 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));
});
您需要使用正则表达式单词边界 http://www.regular-expressions.info/wordboundaries.html.
更改以下行:
var entityRegularExpression = new RegExp(entityText, "g");
To this:
var entityRegularExpression = new RegExp("\\b" + entityText + "\\b", "gi");
这是更新后的 jsfiddle。 http://jsfiddle.net/ehzPQ/14/
注意:我更新了文章文本以包含该单词的一些实例,以便您可以看到它的工作原理。
您还可以更进一步,通过利用正则表达式的功能,使不区分大小写的匹配保留其原始大小写回调 http://www.bennadel.com/blog/1742-Using-Regular-Expressions-In-Javascript-A-General-Overview-.htm。查看这个jsfiddle http://jsfiddle.net/ehzPQ/10/获取代码和示例。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)