JSFiddle - React, Tailwind, and code Playground
HTML
<div id="result"></div>
JavaScript
matches = new Array('fox', 'dog');
originalContent = 'The quick brown fox jumps over the lazy dog but the lazy dog is quick of the mark to catch the brown fox. In general the fox versus the dog is not a good match.';
document.getElementById("result").innerHTML = highlight(originalContent, matches, 2) + '<br>' + preferredHighlight(originalContent, matches, 2);
function highlight(input, matches, max){
var matchesStatistics = new Array();
for(i = 0, c = matches.length; i < c;i++){ // Performance !!!
matchesStatistics[matches[i]] = 0;
}
var re = new RegExp('\\b(?:' + matches.join('|') + ')\\b', 'g');
var highlightedContent = input.replace(re, function(group0){
matchesStatistics[group0]++;
if(matchesStatistics[group0] > max){
return group0;
}else{
return '<b>' + group0 + '</b>';
}
});
return highlightedContent;
}
function preferredHighlight(input, matches, max){
var sentenceRe = new RegExp('[\\s\\S]*?(?:[.?!]|$)', 'g');
var wordRe = new RegExp('\\b(?:' + matches.join('|') + ')\\b', 'g');
var highlightedContent = input.replace(sentenceRe, function(sentence){
var matchesStatistics = 0;
modifiedSentence = sentence.replace(wordRe, function(group0){
matchesStatistics++;
if(matchesStatistics > max){
return group0;
}else{
return '<b>' + group0 + '</b>';
}
});
return modifiedSentence;
});
return highlightedContent;
}