Created
May 10, 2017 01:48
-
-
Save jeanmw/2bdc620d5081f2ce0d950eb29b060834 to your computer and use it in GitHub Desktop.
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
//a nifty piece of code from the internet that provides entertainment | |
function findAndReplace(searchText, replacement, searchNode) { | |
if (!searchText || typeof replacement === 'undefined') { | |
console.log("bad input!"); | |
return; | |
} | |
var regex = typeof searchText === 'string' ? | |
new RegExp(searchText, 'g') : searchText, | |
childNodes = (searchNode || document.body).childNodes, | |
cnLength = childNodes.length, | |
// excludes = 'html,head,style,title,link,meta,script,object,iframe'; | |
excludes=''; | |
while (cnLength--) { | |
var currentNode = childNodes[cnLength]; | |
if (currentNode.nodeType === 1 && | |
(excludes + ',').indexOf(currentNode.nodeName.toLowerCase() + ',') === -1) { | |
arguments.callee(searchText, replacement, currentNode); | |
} | |
if (currentNode.nodeType !== 3 || !regex.test(currentNode.data) ) { | |
continue; | |
} | |
var parent = currentNode.parentNode, | |
frag = (function(){ | |
var html = currentNode.data.replace(regex, replacement), | |
wrap = document.createElement('div'), | |
frag = document.createDocumentFragment(); | |
wrap.innerHTML = html; | |
while (wrap.firstChild) { | |
frag.appendChild(wrap.firstChild); | |
} | |
return frag; | |
})(); | |
parent.insertBefore(frag, currentNode); | |
parent.removeChild(currentNode); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment