Created
July 11, 2016 07:54
-
-
Save wesalvaro/50d507fcfa24bc4041c04c890f67dc0b to your computer and use it in GitHub Desktop.
Simple snippet to do regular expression search in a Chrome Snippet.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
reText = prompt('RegExp?'); | |
backgroundColor = 'rgba(255,255,80,0.5)'; | |
outline = `3px solid ${backgroundColor}`; | |
matchClass = 're-match'; | |
{ // clear old matches | |
const nodes = []; | |
Array.prototype.forEach.call(document.getElementsByClassName(matchClass), node => {nodes.push(node)}); | |
nodes.forEach(node => { node.replaceWith(node.innerText); }); | |
}; | |
[plain, ...complex] = reText.split('/'); | |
complex = complex || []; | |
flags = complex.pop() || 'g'; | |
re = new RegExp(complex.join('/') || plain, flags); | |
console.log(`Searching for /${re.source}/${flags}`); | |
document.body.normalize(); | |
Array.prototype | |
.filter.call(document.body.querySelectorAll('*'), node => re.test(node.innerText)) | |
.reverse() | |
.filter((node, i, arr) => !arr.slice(0, i).some(child => node.contains(child))) | |
.reverse() | |
.map(node => { | |
node.textContent.replace(re, (nMatch, nIndex, nFullString) => { | |
let currIndex = 0; | |
const nodes = []; | |
node.normalize(); | |
node.childNodes.forEach(node => {nodes.push(node)}); // copy to prevent live changes | |
nodes.find(c => { | |
let p = node; | |
if (c.nodeName != '#text') { | |
p = c; | |
c = c.firstChild; | |
} | |
let nextIndex = currIndex + (c ? c.textContent.length : 0); | |
if (nextIndex > nIndex) { | |
const matchIndexStart = nIndex - currIndex; | |
const matchLen = Math.min(c.textContent.length - matchIndexStart, nMatch.length); | |
const matchPart = nMatch.substr(0, matchLen); | |
const newNode = c.splitText(matchIndexStart); | |
newNode.textContent = newNode.textContent.substr(matchLen); | |
nMatch = nMatch.substr(matchLen); | |
nIndex += matchLen; | |
const span = document.createElement('span'); | |
span.innerText = matchPart; | |
span.style.backgroundColor = backgroundColor; | |
span.style.outline = outline; | |
span.classList.add(matchClass) | |
p.insertBefore(span, newNode); | |
} | |
currIndex = nextIndex; | |
return nextIndex >= nIndex + nMatch.length; | |
}); | |
}); | |
return node; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment