检索表达式然后替换它

  1. <!DOCTYPE html>
  2. <html>
  3. <body>
  4.  
  5. <h1>JavaScript 正则表达式</h1>
  6.  
  7. <p>将“microsoft”替换为以下段落中的“baidu”:</p>
  8.  
  9. <button onclick="myFunction()">试一试</button>
  10.  
  11. <p id="demo">Please visit Microsoft and Microsoft!</p>
  12.  
  13. <script>
  14. function myFunction() {
  15. var str = document.getElementById("demo").innerHTML;
  16. var txt = str.replace(/microsoft/i,"baidu");
  17. document.getElementById("demo").innerHTML = txt;
  18. }
  19. </script>
  20.  
  21. </body>
  22. </html>