本文實例講述了JavaScript使用replace函數替換字符串的方法。分享給大家供大家參考。具體如下:
JavaScript通過replace函數替換字符串,下面的代碼將Visit Microsoft中的MicroSoft替換成jb51.net
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 <!DOCTYPE html> <html> <body> <p> Click the button to replace "Microsoft" with "jb51.net" in the paragraph below: </p> <p id="demo">Visit Microsoft!</p> <button onclick="myFunction()">Try it</button> <script> function myFunction() { var str=document.getElementById("demo").innerHTML; var n=str.replace("Microsoft","jb51.net"); document.getElementById("demo").innerHTML=n; } </script> </body> </html>