HTML Encoding of String 1
Given a string and array of keywords, highlight the words in the string that are part of the array of keywords.
const str = "My javaScript FrontEnd Frontdy BackEnd prep";
const words = ["Front", "End", "javaScript"];
console.log(highlight(str, words));
// My <strong>javaScript</strong> <strong>FrontEnd</strong> <strong>Front</strong>dy Back<strong>End</strong> prep
function highlight(str, keywords) {
const uniqueKeyWords = new Set(keywords);
let words = str.split(" ");
let result = words.map((word) => {
let output = "";
if (uniqueKeyWords.has(word)) {
output = "<strong>" + word + "</strong>";
}
else {
for (let i = 0; i < word.length; i++) {
let prefix = word.slice(0, i + 1);
let suffix = word.slice(i + 1);
if (uniqueKeyWords.has(prefix) && uniqueKeyWords.has(suffix)) {
output = "<strong>" + prefix + suffix + "</strong>";
break;
}
else if (uniqueKeyWords.has(prefix)) {
output = "<strong>" + prefix + "</strong>" + suffix;
}
else if (uniqueKeyWords.has(suffix)) {
output = prefix + "<strong>" + suffix + "</strong>";
}
}
}
return output !== "" ? output : word;
});
return result.join(" ");
}