Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace words in the body text

Is there a way to replace the normal text within a table element that is placed within the body of the HTML?

Like replacing "hello" with "hi"?

Please only use JavaScript without jQuery.

like image 487
Wahtever Avatar asked Apr 05 '11 21:04

Wahtever


People also ask

How do I replace a word in a text file?

The Ctrl + F and Command + F keyboard shortcut keys also work in Microsoft Excel and other spreadsheet programs to open the Find and Replace text box. In Microsoft Excel, older versions featured the Edit menu, and the Replace option is found in that menu.


2 Answers

To replace a string in your HTML with another use the replace method on innerHTML:

document.body.innerHTML = document.body.innerHTML.replace('hello', 'hi'); 

Note that this will replace the first instance of hello throughout the body, including any instances in your HTML code (e.g. class names etc..), so use with caution - for better results, try restricting the scope of your replacement by targeting your code using document.getElementById or similar.

To replace all instances of the target string, use a simple regular expression with the global flag:

document.body.innerHTML = document.body.innerHTML.replace(/hello/g, 'hi'); 
like image 114
Dexter Avatar answered Sep 22 '22 23:09

Dexter


I ended up with this function to safely replace text without side effects (so far):

function replaceInText(element, pattern, replacement) {     for (let node of element.childNodes) {         switch (node.nodeType) {             case Node.ELEMENT_NODE:                 replaceInText(node, pattern, replacement);                 break;             case Node.TEXT_NODE:                 node.textContent = node.textContent.replace(pattern, replacement);                 break;             case Node.DOCUMENT_NODE:                 replaceInText(node, pattern, replacement);         }     } } 

It's for cases where the 16kB of findAndReplaceDOMText are a bit too heavy.

like image 36
funky-future Avatar answered Sep 18 '22 23:09

funky-future