1/6/2017 - 9:00 PM

Search and replace all occurrences of a word

Search and replace all occurrences of a word


hello world

hello world Use the default javascript string replace function

<p>Pellentesque habitant hello Hello senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>


// replace hello with hi in all places
// note we search and replace lowercase and uppercase with the  "gi" flag
// if it were only  "g" it would only target lowercase words of hello
// g is the globlal modifier
// i is ignore case
var curInnerHTML = document.body.innerHTML;
curInnerHTML = curInnerHTML.replace(/hello/gi, "hi");
document.body.innerHTML = curInnerHTML;