忽略模糊匹配并使用javascript添加精确的单词模式匹配

忽略模糊匹配并使用javascript添加精确的单词模式匹配

本文介绍了忽略模糊匹配并使用javascript添加精确的单词模式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我的网站创建文本突出显示选项。但我想要精确的单词匹配而不是模糊的单词匹配,我所拥有的代码匹配所有类型的实例,它有一些区分大小写的问题。如果我们采用Jfiddle示例,我只想添加癌症这个词,区分大小写应该是一个问题。并忽略模糊匹配,如癌症和bycanceraous(我知道没有像这样的词,但在这个例子中没有想到任何一个)。我有jfiddle链接

I am trying to create a text highlight option for my website. But I want exact word match instead of fuzzy word match, The code that I have matches all kind of instances and it has some case sensitivity issues. If we take the Jfiddle example, I only want to add the word cancer, case sensitivity should nt be an issue. and ignore fuzzy matches, like cancerous and bycanceraous(I know there is not a word like that, but could not think of any for the example). I have the jfiddle linkhttp://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:

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));
});


推荐答案

你需要利用正则表达式。

You need to utilize Regular Expression's Word Boundaries.

更改以下行:

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

对此:

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



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

您还可以更进一步,通过使用正则表达式的。查看以获取代码和示例。

You can also take it a step further and have the case insensitive matches retain their original case, by utilizing Regular Expression's Callbacks. Check out this jsfiddle for the code and example.

这篇关于忽略模糊匹配并使用javascript添加精确的单词模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 05:13