forked from hail2u/jquery.highlight-search-terms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.highlight-search-terms.js
84 lines (70 loc) · 2.34 KB
/
jquery.highlight-search-terms.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/**
* @preserve jQuery Plugin: Highlight Search Terms v0.4.2
*
* LICENSE: http://hail2u.mit-license.org/2009
*/
/*jslint indent: 2, browser: true, regexp: true */
/*global jQuery, $ */
(function ($) {
"use strict";
// Private: Extract terms from referrer
function extractSearchTerms(ref, o) {
var terms = "";
$.each(o.referrerPatterns, function () {
var pattern = new RegExp(this, "i"),
unsafe;
if (pattern.exec(ref)) {
unsafe = new RegExp(o.unsafeChars, "g");
terms = decodeURIComponent(RegExp.$1).replace(unsafe, "+").replace(/^\+*(.*?)\+*$/, "$1").replace(/\++/g, "|");
return false; // break $.each
}
});
return terms;
}
// Private: Encode entities
function encodeEntities(s) {
return $("<u/>").text(s).html(); // jQuery magic
}
$.fn.highlightSearchTerms = function (options) {
var o = $.extend({}, $.fn.highlightSearchTerms.defaults, options),
ref,
terms,
t,
c,
highlighted;
$.merge(o.referrerPatterns, $.fn.highlightSearchTerms.builtinReferrerPatterns);
ref = o.referrer || document.referrer;
if (ref) {
terms = extractSearchTerms(ref, o);
// Highlight terms
if (terms !== "") {
terms = new RegExp("(" + terms + ")", "gi");
t = encodeEntities(o.tagName);
c = encodeEntities(o.className);
highlighted = "<" + t + " class=\"" + c + "\">$1</" + t + ">";
this.find(":not(iframe, option, script, textarea)").contents().each(function () {
if (this.nodeType === 3) {
var s = encodeEntities(this.nodeValue).replace(terms, highlighted);
$(this).replaceWith(s);
}
});
}
}
return this;
};
// Public: default options
$.fn.highlightSearchTerms.defaults = {
tagName: "em",
className: "highlight",
referrerPatterns: [],
unsafeChars: "[!-*,-/:-@[-`{-~]"
};
// Public: built-in referrer patterns for Google(com|co.jp), Yahoo!(com|co.jp), Bing.
$.fn.highlightSearchTerms.builtinReferrerPatterns = [
"^http://www\\.google\\.com.+[&?]q=([^&]+).*$",
"^http://www\\.google\\.co\\.jp.+[&?]q=([^&]+).*$",
"^http://search\\.yahoo\\.com.+[&?]p=([^&]+).*$",
"^http://search\\.yahoo\\.co\\.jp.+[&?]p=([^&]+).*$",
"^http://www\\.bing\\.com.+[&?]q=([^&]+).*$"
];
}(jQuery));