Why using a selfmade highlighting function is a bad idea
The reason why it's probably a bad idea to start building your own highlighting function from scratch is because you will certainly run into issues that others have already solved. Challenges:
- You would need to remove text nodes with HTML elements to highlight your matches without destroying DOM events and triggering DOM regeneration over and over again (which would be the case with e.g.
- If you want to remove highlighted elements you would have to remove HTML elements with their content and also have to combine the splitted text-nodes for further searches. This is necessary because every highlighter plugin searches inside text nodes for matches and if your keywords will be splitted into several text nodes they will not being found.
- You would also need to build tests to make sure your plugin works in situations which you have not thought about. And I'm talking about cross-browser tests!
Sounds complicated? If you want some features like ignoring some elements from highlighting, diacritics mapping, synonyms mapping, search inside iframes, separated word search, etc. this becomes more and more complicated.
Use an existing plugin
When using an existing, well implemented plugin, you don't have to worry about above named things. The article 10 jQuery text highlighter plugins on Sitepoint compares popular highlighter plugins. This includes plugins of answers from this question.
Have a look at mark.js
- search for keywords separately instead of the complete term
- map diacritics (For example if "justo" should also match "justï¿½")
- ignore matches inside custom elements
- use custom highlighting element
- use custom highlighting class
- map custom synonyms
- search also inside iframes
- receive not found terms
Alternatively you can see this fiddle.
// Highlight "keyword" in the specified context
// Highlight the custom regular expression in the specified context
It's free and developed open-source on GitHub (project reference).