Posted By

Pjotor on 12/10/14


Tagged

jquery text selector


Versions (?)

Multi word case agnostic :contains selector and word highlighter


 / Published in: JavaScript
 

URL: http://pjotor.com

Quick 'n' dirty

  1. var multiWord = function(string){ return new RegExp("(" + string.split(" ").join(")|(") + ")",'gi'); }
  2.  
  3. $.expr[":"].contains = $.expr.createPseudo(function(arg) {
  4. return function( elem ) {
  5. return multiWord(arg).test($(elem).text());
  6. };
  7. });
  8.  
  9. function highLight(string, selector) {
  10. selector = selector || "";
  11. var re = multiWord(string);
  12. $(selector + ":contains(" + string + ")").each(function(){
  13. $(this).html(
  14. $(this).text().replace(re, function($1){
  15. return "<em>" + $1 + "</em>";
  16. })
  17. );
  18. });
  19. }

Report this snippet  

You need to login to post a comment.