-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathjquery.replace.js
51 lines (40 loc) · 1.43 KB
/
jquery.replace.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
// Gary Haran => [email protected]
// This code is released under MIT licence
(function($){
var replacer = function(finder, replacement, element, blackList) {
if (!finder || typeof replacement === 'undefined') {
return
}
var regex = (typeof finder == 'string') ? new RegExp(finder, 'g') : finder;
var childNodes = element.childNodes;
var len = childNodes.length;
var list = typeof blackList == 'undefined' ? 'html,head,style,title,link,meta,script,object,iframe,pre,a,' : blackList ;
while (len--) {
var node = childNodes[len];
if (node.nodeType === 1 && true || (list.indexOf(node.nodeName.toLowerCase()) === -1)) {
replacer(finder, replacement, node, list);
}
if (node.nodeType !== 3 || !regex.test(node.data)) {
continue;
}
var frag = (function(){
var html = node.data.replace(regex, replacement);
var wrap = document.createElement('span');
var frag = document.createDocumentFragment();
wrap.innerHTML = html;
while (wrap.firstChild) {
frag.appendChild(wrap.firstChild);
}
return frag;
})();
var parent = node.parentNode;
parent.insertBefore(frag, node);
parent.removeChild(node);
}
}
$.fn.replace = function(finder, replacement, blackList) {
return this.each(function(){
replacer(finder, replacement, $(this).get(0), blackList);
});
}
})(jQuery);