-
-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
highlight.js
52 lines (48 loc) · 1.6 KB
/
highlight.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
/**
* highlight v3 | MIT license | Johann Burkard <[email protected]>
* Highlights arbitrary terms in a node.
*
* - Modified by Marshal <[email protected]> 2011-6-24 (added regex)
* - Modified by Brian Reavis <[email protected]> 2012-8-27 (cleanup)
*/
var highlight = function($element, pattern) {
if (typeof pattern === 'string' && !pattern.length) return;
var regex = (typeof pattern === 'string') ? new RegExp(pattern, 'i') : pattern;
var highlight = function(node) {
var skip = 0;
if (node.nodeType === 3) {
var pos = node.data.search(regex);
if (pos >= 0 && node.data.length > 0) {
var match = node.data.match(regex);
var spannode = document.createElement('span');
spannode.className = 'highlight';
var middlebit = node.splitText(pos);
var endbit = middlebit.splitText(match[0].length);
var middleclone = middlebit.cloneNode(true);
spannode.appendChild(middleclone);
middlebit.parentNode.replaceChild(spannode, middlebit);
skip = 1;
}
} else if (node.nodeType === 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
for (var i = 0; i < node.childNodes.length; ++i) {
i += highlight(node.childNodes[i]);
}
}
return skip;
};
return $element.each(function() {
highlight(this);
});
};
/**
* removeHighlight fn copied from highlight v5 and
* edited to remove with() and pass js strict mode
*/
$.fn.removeHighlight = function() {
return this.find("span.highlight").each(function() {
this.parentNode.firstChild.nodeName;
var parent = this.parentNode;
parent.replaceChild(this.firstChild, this);
parent.normalize();
}).end();
};