jquery.highlight.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /**
  2. * highlight 1.0.0
  3. * Licensed under MIT
  4. *
  5. * Copyright (c) 2016 yjteam
  6. * http://yjteam.co.kr
  7. *
  8. * GitHub Repositories
  9. * https://github.com/yjseo29/highlight.js
  10. */
  11. if (typeof jQuery === 'undefined') {
  12. throw new Error('JavaScript requires jQuery')
  13. }
  14. +function ($) {
  15. 'use strict';
  16. var version = $.fn.jquery.split(' ')[0].split('.')
  17. if ((version[0] < 2 && version[1] < 9) || (version[0] == 1 && version[1] == 9 && version[2] < 1)) {
  18. throw new Error('JavaScript requires jQuery version 1.9.1 or higher')
  19. }
  20. }(jQuery);
  21. +function ($) {
  22. $.fn.highlight = function (word, options) {
  23. var option = $.extend({
  24. background: "#ffff00",
  25. color: "#000",
  26. bold: false,
  27. class: "",
  28. ignoreCase: true,
  29. wholeWord: true
  30. }, options);
  31. var findCnt = 0;
  32. if (this.length == 0) {
  33. throw new Error('Node was not found')
  34. }
  35. var $el = $('<span style="color:' + option.color + ';"></span>');
  36. if (option.bold) {
  37. $el.css("font-weight", "bold");
  38. }
  39. if (option.background != "") {
  40. $el.css("background", option.background);
  41. }
  42. if (option.class != "") {
  43. $el.addClass(option.class);
  44. }
  45. if (option.wholeWord) {
  46. word = "\\b" + escapeRegExp(word) + "\\b";
  47. }
  48. var re = new RegExp(word, option.ignoreCase == true ? 'gi' : 'g');
  49. this.each(function () {
  50. var content = $(this).html();
  51. $(this).html(content.replace(re, function (t) {
  52. findCnt++;
  53. $el.text(t);
  54. return $el.get(0).outerHTML;
  55. }));
  56. });
  57. return findCnt;
  58. function escapeRegExp(string) {
  59. return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
  60. }
  61. }
  62. }(jQuery);