JS replace()方法-字串首字母大寫

來源:互聯網
上載者:User

標籤:des   style   blog   http   color   使用   os   io   

replace() 方法用於在字串中用一些字元替換另一些字元,或替換一個與Regex匹配的子串。

replace()方法有兩個參數,第一個參數是Regex,Regex如果帶全域標誌/g,則是代表替換所有匹配的字串,否則是只替換第一個匹配串。
第二個參數可以是字串,也可以是函數。$1、$2...表示與Regex匹配的文本。

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() 方法用於在字串中用一些字元替換另一些字元,或替換一個與Regex匹配的子串。<br />replace()方法有兩個參數,第一個參數是Regex,Regex如果帶全域標誌/g,則是代表替換所有匹配的字串,否則是只替換第一個匹配串。<br />13 第二個參數可以是字串,也可以是函數。$1、$2...表示與Regex匹配的文本。</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>

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.