-
Notifications
You must be signed in to change notification settings - Fork 146
Expand file tree
/
Copy pathfindAndReplaceDOMText.js
More file actions
265 lines (234 loc) · 7.88 KB
/
findAndReplaceDOMText.js
File metadata and controls
265 lines (234 loc) · 7.88 KB
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
/**
* findAndReplaceDOMText
* @author James Padolsey http://james.padolsey.com
* @license http://unlicense.org/UNLICENSE
*
* Matches the text of a DOM node against a regular expression
* and replaces each match (or node-separated portions of the match)
* in the specified element.
*
* Example: Wrap 'test' in <em>:
* <p id="target">This is a test</p>
* <script>
* findAndReplaceDOMText(
* /test/,
* document.getElementById('target'),
* 'em'
* );
* </script>
*/
window.findAndReplaceDOMText = (function() {
/**
* findAndReplaceDOMText
*
* Locates matches and replaces with replacementNode
*
* @param {RegExp} regex The regular expression to match
* @param {Node} node Element or Text node to search within
* @param {String|Element|Function} replacementNode A NodeName,
* Node to clone, or a function which returns a node to use
* as the replacement node.
*/
function findAndReplaceDOMText(regex, node, replacementNode) {
var m, index, matches = [], text = _getText(node);
var replaceFn = _genReplacer(replacementNode);
if (!text) { return; }
if (regex.global) {
while (m = regex.exec(text)) {
if (!m[0]) throw 'findAndReplaceDOMText cannot handle zero-length matches';
matches.push([regex.lastIndex - m[0].length, regex.lastIndex, m]);
}
} else {
m = text.match(regex);
index = text.indexOf(m[0]);
if (!m[0]) throw 'findAndReplaceDOMText cannot handle zero-length matches';
matches.push([index, index + m[0].length, m]);
}
if (matches.length) {
_stepThroughMatches(node, matches, replaceFn);
}
}
/**
* Gets aggregate text of a node without resorting
* to broken innerText/textContent
*/
function _getText(node) {
if (node.nodeType === 3) {
return node.data;
}
var txt = '';
if (node = node.firstChild) do {
txt += _getText(node);
} while (node = node.nextSibling);
return txt;
}
/**
* Steps through the target node, looking for matches, and
* calling replaceFn when a match is found.
*/
function _stepThroughMatches(node, matches, replaceFn) {
var after, before,
startNode,
endNode,
startNodeIndex,
endNodeIndex,
innerNodes = [],
atIndex = 0,
curNode = node,
matchLocation = matches.shift(),
matchIndex = 0;
out: while (true) {
if (curNode.nodeType === 3) {
if (!endNode && curNode.length + atIndex >= matchLocation[1]) {
// We've found the ending
endNode = curNode;
endNodeIndex = matchLocation[1] - atIndex;
} else if (startNode) {
// Intersecting node
innerNodes.push(curNode);
}
if (!startNode && curNode.length + atIndex > matchLocation[0]) {
// We've found the match start
startNode = curNode;
startNodeIndex = matchLocation[0] - atIndex;
}
atIndex += curNode.length;
}
if (startNode && endNode) {
curNode = replaceFn({
startNode: startNode,
startNodeIndex: startNodeIndex,
endNode: endNode,
endNodeIndex: endNodeIndex,
innerNodes: innerNodes,
match: matchLocation[2],
matchIndex: matchIndex
});
// replaceFn has to return the node that replaced the endNode
// and then we step back so we can continue from the end of the
// match:
atIndex -= (endNode.length - endNodeIndex);
startNode = null;
endNode = null;
innerNodes = [];
matchLocation = matches.shift();
matchIndex++;
if (!matchLocation) {
break; // no more matches
}
} else if (curNode.firstChild || curNode.nextSibling) {
// Move down or forward:
curNode = curNode.firstChild || curNode.nextSibling;
continue;
}
// Move forward or up:
while (true) {
if (curNode.nextSibling) {
curNode = curNode.nextSibling;
break;
} else if (curNode.parentNode !== node) {
curNode = curNode.parentNode;
} else {
break out;
}
}
}
}
var reverts;
/**
* Reverts the last findAndReplaceDOMText process
*/
findAndReplaceDOMText.revert = function revert() {
for (var i = 0, l = reverts.length; i < l; ++i) {
reverts[i]();
}
reverts = [];
};
/**
* Generates the actual replaceFn which splits up text nodes
* and inserts the replacement element.
*/
function _genReplacer(nodeName) {
reverts = [];
var makeReplacementNode;
if (typeof nodeName != 'function') {
var stencilNode = nodeName.nodeType ? nodeName : document.createElement(nodeName);
makeReplacementNode = function(fill) {
var clone = document.createElement('div'),
el;
clone.innerHTML = stencilNode.outerHTML;
el = clone.firstChild;
if(fill) {
el.appendChild(document.createTextNode(fill));
}
return el;
};
} else {
makeReplacementNode = nodeName;
}
return function replace(range) {
var startNode = range.startNode,
endNode = range.endNode,
matchIndex = range.matchIndex;
if (startNode === endNode) {
var node = startNode;
if (range.startNodeIndex > 0) {
// Add `before` text node (before the match)
var before = document.createTextNode(node.data.substring(0, range.startNodeIndex));
node.parentNode.insertBefore(before, node);
}
// Create the replacement node:
// var el = stencilNode.cloneNode(false);
//el.appendChild(document.createTextNode(range.match[0]));
var el = makeReplacementNode(range.match[0], matchIndex);
node.parentNode.insertBefore(el, node);
if (range.endNodeIndex < node.length) {
// Add `after` text node (after the match)
var after = document.createTextNode(node.data.substring(range.endNodeIndex));
node.parentNode.insertBefore(after, node);
}
node.parentNode.removeChild(node);
reverts.push(function() {
var pnode = el.parentNode;
pnode.insertBefore(el.firstChild, el);
pnode.removeChild(el);
pnode.normalize();
});
return el;
} else {
// B4 - innerNodes - After
var before = document.createTextNode(startNode.data.substring(0, range.startNodeIndex));
var after = document.createTextNode(endNode.data.substring(range.endNodeIndex));
var elA = makeReplacementNode(startNode.data.substring(range.startNodeIndex), matchIndex);
var elB = makeReplacementNode(endNode.data.substring(0, range.endNodeIndex), matchIndex);
var innerEls = [];
//elA.appendChild(document.createTextNode());
startNode.parentNode.insertBefore(before, startNode);
startNode.parentNode.insertBefore(elA, startNode);
startNode.parentNode.removeChild(startNode);
endNode.parentNode.insertBefore(elB, endNode);
endNode.parentNode.insertBefore(after, endNode);
endNode.parentNode.removeChild(endNode);
for (var i = 0, l = range.innerNodes.length; i < l; ++i) {
var innerNode = range.innerNodes[i];
var innerEl = makeReplacementNode(innerNode.data, matchIndex);
innerNode.parentNode.replaceChild(innerEl, innerNode);
innerEls.push(innerEl);
}
reverts.push(function() {
innerEls.unshift(elA);
innerEls.push(elB);
for (var i = 0, l = innerEls.length; i < l; ++i) {
var el = innerEls[i];
var pnode = el.parentNode;
pnode.insertBefore(el.firstChild, el);
pnode.removeChild(el);
pnode.normalize();
}
});
return elB;
}
};
}
return findAndReplaceDOMText;
}());