replace() 方法用於在字符串中用一些字符替換另一些字符,或替換一個與正則表達式匹配的子串。
replace()方法有兩個參數,第一個參數是正則表達式,正則表達式如果帶全局標志/g,則是代表替換所有匹配的字符串,否則是只替換第一個匹配串。
第二個參數可以是字符串,也可以是函數。$1、$2...表示與正則表達式匹配的文本。
There are many ways we can make a difference. Global change starts with you. Sign up for our free newsletter today.
輸出:There Are Many Ways We Can Make A Difference. Global Change Starts With You. Sign Up For Our Free Newsletter Today.
源代碼如下:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" Content="text/html; charset=utf-8;"> 5 <title> JS replace方法 </title> 6 <meta name="author" content="rainna" /> 7 <meta name="keywords" content="rainna's js lib" /> 8 <meta name="description" content="JS replace方法" /> 9 </head> 10 <body> 11 <h1>使用JS的replace()方法把所有單詞的首字母大寫</h1> 12 <p>replace() 方法用於在字符串中用一些字符替換另一些字符,或替換一個與正則表達式匹配的子串。<br />replace()方法有兩個參數,第一個參數是正則表達式,正則表達式如果帶全局標志/g,則是代表替換所有匹配的字符串,否則是只替換第一個匹配串。<br /> 13 第二個參數可以是字符串,也可以是函數。$1、$2...表示與正則表達式匹配的文本。</p> 14 <p id="word">There are many ways we can make a difference. Global change starts with you. Sign up for our free newsletter today.</p> 15 <a href="" id="replaceBtn">替換</a> 16 17 <script> 18 var replaceFunc = function(){ 19 var word = document.getElementById('word').innerText.toString(), 20 btn = document.getElementById('replaceBtn'); 21 22 var func1 = function(str){ 23 return str.replace(/\b\w+\b/g,function(word){ 24 return word.substring(0,1).toUpperCase() + word.substring(1); 25 }); 26 } 27 28 btn.onclick = function(event){ 29 event.preventDefault(); 30 console.log(func1(word)); 31 } 32 } 33 34 replaceFunc(); 35 </script> 36 </body> 37 </html>
