當(dāng)前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
JS replace()方法-字符串首字母大写
生活随笔
收集整理的這篇文章主要介紹了
JS replace()方法-字符串首字母大写
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
replace() 方法用于在字符串中用一些字符替換另一些字符,或替換一個(gè)與正則表達(dá)式匹配的子串。
replace()方法有兩個(gè)參數(shù),第一個(gè)參數(shù)是正則表達(dá)式,正則表達(dá)式如果帶全局標(biāo)志/g,則是代表替換所有匹配的字符串,否則是只替換第一個(gè)匹配串。
第二個(gè)參數(shù)可以是字符串,也可以是函數(shù)。$1、$2...表示與正則表達(dá)式匹配的文本。
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() 方法用于在字符串中用一些字符替換另一些字符,或替換一個(gè)與正則表達(dá)式匹配的子串。<br />replace()方法有兩個(gè)參數(shù),第一個(gè)參數(shù)是正則表達(dá)式,正則表達(dá)式如果帶全局標(biāo)志/g,則是代表替換所有匹配的字符串,否則是只替換第一個(gè)匹配串。<br /> 13 第二個(gè)參數(shù)可以是字符串,也可以是函數(shù)。$1、$2...表示與正則表達(dá)式匹配的文本。</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>?
轉(zhuǎn)載于:https://www.cnblogs.com/zourong/p/3891047.html
總結(jié)
以上是生活随笔為你收集整理的JS replace()方法-字符串首字母大写的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: pthread多线程编程的学习小结
- 下一篇: 一种基于openflow的虚拟化层软件f