Guest User

Untitled

a guest
Oct 22nd, 2017
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. function highlightText(params) {
  2. var p = {
  3. query: [],
  4. isAppend: true,
  5. searchAttr: 'xxxxx'
  6. };
  7. $.extend(p, params);
  8.  
  9. var phrases = p.query,
  10. searchAttr = p.searchAttr,
  11. isAppend = p.isAppend;
  12.  
  13. var source = this.html()
  14. .replace(/[\n|\t]+/gi, '')
  15. .replace(/\s+/gi, ' ')
  16. .replace(/> /gi, '>')
  17. .replace(/(\w)</gi, function (m, w) {
  18. return (w + " <");
  19. });
  20.  
  21. phrases.forEach(function (str) {
  22. source = source.replace(makeRegexp(str), emulateSelection);
  23. });
  24.  
  25. var result = {
  26. $el: this
  27. };
  28.  
  29. if (isAppend) {
  30. result.$search = this.html(source).find("[search=" + searchAttr + "]");
  31. } else {
  32. var $source = $(source);
  33. result.$source = $source;
  34. result.$search = $source.find("[search=" + searchAttr + "]");
  35. }
  36.  
  37. return result;
  38.  
  39. function makeRegexp(s) {
  40. var space = '( )?(<span[^>]*>)?(</span[^>]*>)?( )?';
  41. var result = s.replace(/\s/gi, space);
  42. return new RegExp(space + result + space, "gi");
  43. }
  44.  
  45. function emulateSelection(htmlPiece) {
  46. return htmlPiece
  47. .replace(/(?!=>)[^><]+(?=<)/g, wrapWords)
  48. .replace(/^[^><]+/, wrapWords)
  49. .replace(/[^><]+$/, wrapWords)
  50. .replace(/^[^><]+$/, wrapWords);
  51. }
  52.  
  53. function wrapWords(plainPiece) {
  54. return '<span search="' + searchAttr + '">' + plainPiece + '</span>';
  55. }
  56. };
Add Comment
Please, Sign In to add comment