Created
April 11, 2018 18:24
-
-
Save s-light/d34cb4c944d004f8f22f27011feb0f38 to your computer and use it in GitHub Desktop.
replace in all text nodes (html dom javascript)
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
function replace_in_textnodes(search_string, replace_string) { | |
console.group('replace_in_pre'); | |
// based on: https://stackoverflow.com/a/10730777/574981 | |
const walk = document.createTreeWalker( | |
document, | |
NodeFilter.SHOW_TEXT, | |
null, | |
false | |
); | |
let replace_counter = 0; | |
const search_regex = new RegExp(search_string, 'gim'); | |
var text_node; | |
while (text_node = walk.nextNode()) { | |
let original_content = text_node.nodeValue; | |
let new_content = original_content.replace( | |
search_regex, | |
replace_string | |
); | |
if (new_content != original_content) { | |
replace_counter += 1; | |
text_node.nodeValue = new_content; | |
} | |
} | |
console.log('found ' + replace_counter + ' occurrences.'); | |
console.groupEnd(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment