JS replace()方法-字符串首字母大写
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>