JSFiddle - React, Tailwind, and code Playground
by CrossEye
JavaScript
var arrString = "apple, banana, monkey, sugar",
text = "This a nice monkey zoo with banana trees.";
var arr = arrString.split(", ");
var found = [], foundIndices = [];
var test = new RegExp("\\b" + arr.join("\\b|\\b") + "\\b", "g");
var newText = text.replace(test, function(word) {
if (found.indexOf(word) < 0) {
found.push(word);
};
var index = arr.indexOf(word);
if (foundIndices.indexOf(index) < 0) {
foundIndices.push(index);
}
return "<b>" + word + "</b>";
});
foundIndices.sort(function(a, b) {return b - a;});
foundIndices.forEach(function(index) {arr.splice(index, 1);});
var log = function(msg) {
$("body").append(msg).append("<br><br>");
}
log(arrString);
log("The text contains " + found.join(", ") + ".");
log(newText);
log("These array itmes are left: " + arr.join(", ") + ".");