-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
52 lines (36 loc) · 1.91 KB
/
Copy pathcontent.js
File metadata and controls
52 lines (36 loc) · 1.91 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
// input taken from replace.js
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.action === "replaceText") {
const { oldText, repText, isNotCaseSensitive } = message;
const escapedOldText = oldText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const regexFlags = isNotCaseSensitive ? 'g' : 'gi';
const regex = new RegExp(escapedOldText, regexFlags);
function replaceTextNodes(node) {
if (node.nodeType === Node.TEXT_NODE) {
const matches = [...node.textContent.matchAll(regex)];
let newText = node.textContent;
for (const match of matches) {
const matchedText = match[0];
const matchIndex = match.index;
if (isNotCaseSensitive) {
newText = newText.substring(0, matchIndex) + repText + newText.substring(matchIndex + matchedText.length);
} else {
// to keep case sensitive
const casePreservedText = repText.split('').map((char, i) => {
// ie. if matchedText has a character at position i, preserve case
return matchedText[i] && matchedText[i].toUpperCase() === matchedText[i]
? char.toUpperCase()
: char.toLowerCase();
}).join('');
newText = newText.substring(0, matchIndex) + casePreservedText + newText.substring(matchIndex + matchedText.length);
} // end else
} //end for
node.textContent = newText;
} else {
// recursively goes through child nodes
node.childNodes.forEach(replaceTextNodes);
}
}
replaceTextNodes(document.body);
} // end message listener
});