jquery.highlight.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. highlight v3
  3. Highlights arbitrary terms.
  4. <http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html>
  5. MIT license.
  6. Johann Burkard <http://johannburkard.de> <mailto:jb@eaio.com>
  7. Julio Montoya <gugli100@gmail.com> fixes for the Glossary tool to strict search
  8. */
  9. jQuery.fn.highlight = function(pat,real_code) {
  10. function innerHighlight(node, pat) {
  11. var skip = 0;
  12. if (node.nodeType == 3 ) {
  13. // Highlight all coincidences
  14. //var pos = node.data.toUpperCase().indexOf(pat);
  15. //Highlight strict, exact words
  16. var SearchRegExp = new RegExp("(\\b|\\B)"+pat+"(\\b|\\B)","gi");
  17. var pos = node.nodeValue.search(SearchRegExp);
  18. if (pos >= 0 ) {
  19. var spannode = document.createElement('a');
  20. spannode.className = 'glossary-ajax';
  21. spannode.style.color = '#084B8A';
  22. spannode.style.fontWeight='100';
  23. spannode.style.textDecoration = 'none';
  24. spannode.name = 'link'+real_code;
  25. spannode.href = '#';
  26. var SearchRegExp = new RegExp("(" + pat +")","gi");
  27. var MatchRegExp = node.nodeValue.match(SearchRegExp);
  28. if (MatchRegExp == null) {
  29. MatchRegExp = new Array();
  30. }
  31. if (MatchRegExp.length > 0 && node.nodeValue[pat.length+1] != '') {
  32. var middlebit = node.splitText(pos);
  33. var endbit = middlebit.splitText(pat.length);
  34. if (endbit.nodeValue[0] == null || endbit.nodeValue[0] == ' ' || endbit.nodeValue[0] == '.' || endbit.nodeValue[0] == ',' || endbit.nodeValue[0] == ';' || endbit.nodeValue[0] == '"') {
  35. var middleclone = middlebit.cloneNode(true);
  36. spannode.appendChild(middleclone);
  37. middlebit.parentNode.replaceChild(spannode, middlebit);
  38. }
  39. }
  40. skip = 1;
  41. }
  42. } else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
  43. for (var i = 0; i <node.childNodes.length ; ++i) {
  44. i += innerHighlight(node.childNodes[i], pat);
  45. }
  46. }
  47. return skip;
  48. }
  49. return this.each(function() {
  50. innerHighlight(this, pat.toUpperCase());
  51. });
  52. };
  53. jQuery.fn.removeHighlight = function() {
  54. return this.find("a.highlight").each(function() {
  55. this.parentNode.firstChild.nodeName;
  56. with (this.parentNode) {
  57. replaceChild(this.firstChild, this);
  58. normalize();
  59. }
  60. }).end();
  61. };