Replace words in the body text

Wahtever picture Wahtever · Apr 5, 2011 · Viewed 277.1k times · Source

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.

Answer

Dexter picture Dexter · Apr 5, 2011

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');