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 link
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));
});
You need to utilize Regular Expression’s Word Boundaries.
Change the following line:
To this:
Here’s the updated jsfiddle.
Note: I updated the article text to contain some instances of the word so you could see it work.
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.