Explain Codes LogoExplain Codes Logo

Replace words in the body text

javascript
prompt-engineering
functions
callbacks
Alex KataevbyAlex Kataev·Dec 22, 2024
TLDR

Quick tip for replacing text within the HTML page: use JavaScript’s replace() method in conjunction with textContent or innerText. This approach keeps your DOM unscathed:

document.body.textContent = document.body.textContent.replace(/oldText/g, 'newText');

The /g switch ensures all occurrences are swapped out. This approach beats innerHTML manipulation, dodging potential issues with breaking scripts or event handlers.

Safe text replacement

Touching the DOM can be like a game of Jenga - one wrong move and your beautiful tower of code could come crashing down. JavaScript's replace(), combined with regex, helps you play it safe.

Precise targeting within complex structures

If your DOM structure is more of a dense forest rather than a manicured garden, try querySelectorAll. It hand-picks particular elements before making changes:

// Searches for targets, avoids friendly fire document.querySelectorAll('table td').forEach(function(td) { td.textContent = td.textContent.replace(/oldText/g, 'newText'); });

Recursion for nested changes

Navigating the DOM can get nested, complex. Luckily, recursion can be your breadcrumb trail:

// Like a game of Inception, but for code function replaceText(node, searchRegex, replaceString) { if (node.nodeType === 3) { // Text node node.nodeValue = node.nodeValue.replace(searchRegex, replaceString); } else { node.childNodes.forEach(child => replaceText(child, searchRegex, replaceString)); } } replaceText(document.body, /oldText/g, 'newText');

Test, rehearse, and mimic a Broadway production before a live run. This helps avoid breaking links and unexpected JavaScript intersections.

Use helper libraries

findAndReplaceDOMText could be your beneficial associate when it comes to more complex text replacements. It handles regex-based replacements while remaining respectful to your DOM:

findAndReplaceDOMText(document.body, { find: /oldText/g, replace: 'newText' });

Performance-focused approach

As they say, not all heroes wear capes. For peak performance, using lighter functions for easier substitutions while leaving the heavy-duty operations to robust libraries is a wise approach.

Shield your scripts & styles

While replacing text, it's vital to avoid substitutions within <script> or <style> tags:

// Better safe than sorry function isSafeNode(node) { return !(/SCRIPT|STYLE/.test(node.parentNode.tagName)); } // Takes 'safe' to another level function replaceSafeText(node, searchRegex, replaceString) { if (node.nodeType === 3 && isSafeNode(node)) { // Text node node.nodeValue = node.nodeValue.replace(searchRegex, replaceString); } else { node.childNodes.forEach(child => replaceSafeText(child, searchRegex, replaceString)); } } replaceSafeText(document.body, /oldText/g, 'newText');

Trigger replacements at right time

Wait till the party starts before making your grand entrance! Executing replacements after the document loads ensures smooth DOM interactions:

// Better late than never; we're fashionably on time document.addEventListener('DOMContentLoaded', function() { replaceSafeText(document.body, /oldText/g, 'newText'); });