I’m using JQueryUI’s autocomplete fill in a textbox. This string can contain multiple words that I do a search on and return the search results to. I have already completed writing up about the retrieval of the autocomplete results across these multiple terms, and now need help bolding the words in my results.
For example, typing in “dog i” should result in the following results (ignore the bad spacing with the i’s), where my three keywords are bolded:
“The dog i s a brown one.”
“The brown dog i s my fr i end.”
The general solution seems to be using String.replace and a regex that adds some additional HTML wrapper to the keywords in my results. However, the issue is, because I have multiple keywords, I might run into the situation where I wrap the contents of the newly added HTML. Continuing the above example, the “i” would cause the “i” in “weight” of dog to get wrapped:
"The brown <span style='font-we<span style='font-weight:bold'>i</span>ght:bold'>dog</span> <span style='font-weight:bold'>i</span>s my fr<span style='font-weight:bold'>i</span>end."
How do I prevent my HTML from getting rewrapped by HTML? Thanks.
Here is my code:
var regex;
for (var i = 0; i < item.keywords.length; i++) {
regex = new RegExp(item.keywords[i], "i");
display = display.replace(regex, "<span style='font-weight:bold'>" +
item.keywords[i] + "</span>");
}
DEMO.