I’m 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 there’s some sort of tokenizing problem, but I’m 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 parent’s string and there are definitions attached at each node…but I can’t quite turn it into an idea, plus i feel like that’s 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.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.