I am faced with a challenge of highlighting specific words within text received from an ajax response, before generating HTML code and inserting it into the DOM. At the moment, I am utilizing the following code snippet:
function highlightWords(line, word, htmltag) {
var tag = htmltag || ["<b>", "</b>"];
var regex = new RegExp('(' + preg_quote(word) + ')', 'gi');
return line.replace(regex, tag[0] + "$1" + tag[1]);
}
function preg_quote(str) {
return (str + '').replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<<>>\|\:])/g, "\\$1");
}
However, this method does not allow for highlighting individual words if the query is a phrase like sit behind
. It highlights the entire phrase as one unit rather than each word separately. Additionally, it does not take HTML tags into consideration leading to less aesthetically pleasing results when the query includes a term like span
...
I have come across different libraries that handle text highlighting more effectively, such as or
However, these libraries tend to focus on highlighting existing content within the DOM.
My scenario involves receiving an ajax response which needs to be converted into HTML using JS before being inserted into the parent container using DOM7 (similar to jQuery). Hence, I prefer to highlight the text before generating the HTMLString and pasting it into the DOM.
Any suggestions?