Inspired of the answer @SquareCat mentionned in comments, I think I've made something working great.
You did not indicate how you call this script, by the way...
So I may be wrong on the way you use it.
But I reproduced your problem in this CodePen.
Then, I made it working in this CodePen, using 4 words that were all correctly found 3 times.
In the below snippet, I'm pushing my luck to 7 words 5 times.
;)
jQuery.fn.highlight = function (str, className) {
var target = $(this)[0].innerHTML;
var replacement = "<span class='"+className+"'>"+str+"</span>";
return target.replace(new RegExp(str, 'gi'), replacement );
}
$("#go").on("click",function(){
var words = $("#search").val().split(" ");
var colors = ["yellow","pink","cyan","orange","grey","blue","red"];
for(i=0;i<words.length;i++){
$(document).find("#test").html( $(document).find("#test").highlight(words[i],colors[i]) );
}
});
$("#reset").on("click",function(){
$("#test").find("span").each(function(){
var temp = $(this).html();
$(this).replaceWith(temp);
});
});
.yellow{
background-color:yellow;
}
.pink{
background-color:pink;
}
.cyan{
background-color:cyan;
}
.orange{
background-color:orange;
}
.grey{
background-color:grey;
}
.blue{
background-color:blue;
color:white;
}
.red{
background-color:red;
color:white;
}
input{
width:20em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
This was an interesting problem. Now some part of speach are correctly identified and some part of speach are also correctly identified. Some Other part of speach are identified many times correctly. So to have them correctly identified, some are part of speach is some part of speach are correctly identified. And I know that this sentence is horrible! ;)
</div>
<br>
<input type="text" id="search" value="some part of speach are correctly identified">
<button id="go">GO</button>
<button id="reset">RESET</button>