Im implementing glossary/dictionary in Javascript.  It is populated with a set of terms and their definitions internally, then gets handed jQuery elements and searches the HTML, replacing any of the terms it finds with a link to their definition.  The current implementation runs by forEaching the dictionary over the HTML and running String.prototype.replace() where relevant.  Examples of terms would be credit and credit report.Naturally, this causes problems with our substrings- if the dictionary defines both credit and credit report, then the current implementation creates one link for each when it encounters credit report in the HTML.Obviously theres some sort of tokenizing problem, but Im not sure how to handle it.  I have some inkling of an idea based on a tree, where each child node adds a chunk to the parents string and there are definitions attached at each nodebut I cant quite turn it into an idea, plus i feel like thats overengineered.Is there a canonical way to only match the longest term?  This seems like a variant on longest-substring, but I've had trouble identifying the conceptual pieces that match up.
Find longest match from a set of possibles, given a string
algorithms;javascript