RegExp實現字符替換
阿新 • • 發佈:2018-11-02
code try color itl cti 實現 paul rap ner
將字符串組中的所有Paul替換成Ringo,g:執行全局匹配,查找所有匹配而非在找到第一個匹配後停止;\b:匹配單詞邊界,劃分匹配字符的起始範圍
<!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(/\bPaul\b/g,"Ringo");
document.getElementById("demo").innerHTML = txt;
}
RegExp實現字符替換