将字符串组中的所有Paul替换成Ringo,g:执行全局匹配,查找所有匹配而非在找到第一个匹配后停止;:匹配单词边界,划分匹配字符的起始范围
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <script type="text/javascript" src="JS.js"></script> </head> <body> <p>Replace "Paul" with "Ringo" in the paragraph below:</p> <button onclick="myFunction()">Try it</button> <p id="demo">Paul,Paula,Pauline,paul,Paul</p> </body> </html>
JS部分: function myFunction() { var str = document.getElementById("demo").innerHTML; var txt = str.replace(/Paul/g,"Ringo"); document.getElementById("demo").innerHTML = txt; }