JavaScript RegExp based highlighting for MooTools and jQuery
How it works
A regular expression looks for text outside HTML tags. It uses a callback function to perform replacements to simulate native lookahead support.
When is this sort of replacement suitable ?
- Remote HTML responses (ajax) highlighting
- Autocompleters suggestion highlighting
- User-typed HTML, WYSIWIGs, etc.
Generally speaking, the only downside of this method, since it deals with the innerHTML, is that all attached events and properties are lost when the replacement is performed.
Note: this code is designed to match only beginning of words. If you want to match anywhere, remove \\b from the regular expression. And if you expect <script> tags, definitely don’t use it.
MooTools version (demo)
Element.implement({ highlight: function(search, insensitive, klass){ var regex = new RegExp('(<[^>]*>)|(\\b'+ search.escapeRegExp() +')', insensitive ? 'ig' : 'g'); return this.set('html', this.get('html').replace(regex, function(a, b, c){ return (a.charAt(0) == '<') ? a : '<strong class="'+ klass +'">' + c + '</strong>'; })); } });
jQuery version (demo)
jQuery.fn.extend({ highlight: function(search, insensitive, klass){ var regex = new RegExp('(<[^>]*>)|(\\b'+ search.replace(/([-.*+?^${}()|[\]\/\\])/g,"\\$1") +')', insensitive ? 'ig' : 'g'); return this.html(this.html().replace(regex, function(a, b, c){ return (a.charAt(0) == '<') ? a : '<strong class="'+ klass +'">' + c + '</strong>'; })); } });
-
[...] article can be reached here. It helped me a lot in highlighting the searches in result. It can be used anywhere with any script [...]
-
[...] (jQuery code slightly adapted from devthought’s JavaScript RegExp based highlighting.) [...]
[...] (le code jQuery a été adapté de devthought’s JavaScript RegExp based highlighting.) [...]