Show Output
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>JavaScript RegExp to Replace All Words inside a String</title> </head> <body> <h4>Original String</h4> <p>if the facts do not fit the theory, change the facts.</p> <h4>String After Replacement</h4> <script> /* Define function for escaping user input to be treated as a literal string within a regular expression */ function escapeRegExp(string){ return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } /* Define functin to find and replace specified term with replacement string */ function replaceAll(str, term, replacement) { return str.replace(new RegExp(escapeRegExp(term), 'g'), replacement); } /* Testing our replaceAll() function */ var myStr = 'if the facts do not fit the theory, change the facts.'; var newStr = replaceAll(myStr, 'facts', 'statistics') // Printing the modified string document.write('<p>' + newStr + '</p>'); </script> </body> </html>