替换字符串中的字符 - replace()

  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">请访问 Microsoft!</p>
  12.  
  13. <script>
  14. function myFunction() {
  15. var str = document.getElementById("demo").innerHTML;
  16. var txt = str.replace("Microsoft","baidu");
  17. document.getElementById("demo").innerHTML = txt;
  18. }
  19. </script>
  20.  
  21. </body>
  22. </html>