search.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. jQuery.fn.highlightPattern = function (patt, className)
  2. {
  3. // check if patt starts or ends with non-word character
  4. // and set regex boundary accordingly.
  5. var start = '\\b(';
  6. var end = ')\\b';
  7. if (/\W/.test(patt.charAt(0))) {
  8. var start = '\(?=\\W\)(';
  9. };
  10. if (/\W/.test(patt.charAt(patt.length - 1))) {
  11. var end = ')\(?!\\w\)';
  12. }
  13. // escape regex metacharacters that may be in the patt
  14. var epatt = patt.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1")
  15. // patt is a space separated list of strings - we want to highlight
  16. // an occurrence of any of these strings as a separate word.
  17. var regex = new RegExp(start + epatt.replace(/ /g, '| ') + end, 'gi');
  18. return this.each(function ()
  19. {
  20. this.innerHTML = this.innerHTML.replace(regex,
  21. '<span class=\'' + className + '\'>' + '$1' + '</span>');
  22. });
  23. };
  24. function toggleMatches(obj) {
  25. var pattern = $('#pattern').text();
  26. var matches = obj.next('.matches')
  27. matches.slideToggle(300);
  28. matches.highlightPattern(pattern, 'highlighted');
  29. if (obj.html() == '[show matches]') {
  30. obj.html('[hide matches]');
  31. } else {
  32. obj.html('[show matches]');
  33. };
  34. }
  35. $(function() {
  36. $('a.showmatch').attr('onClick', 'toggleMatches($(this));');
  37. $('pre.matches').hide();
  38. $('a.showmatch').show();
  39. });