js中應用正則表達式轉換大小寫,代碼很簡單,看代碼:
以下首字母大寫,其它字母小寫
<script type="text/javascript"> function replaceReg(reg,str){ str = str.toLowerCase(); return str.replace(reg,function(m){return m.toUpperCase()}) } var reg = /\b(\w)|\s(\w)/g; var str = 'share javascript'; var str2 = 'SHARE JAVASCRIPT'; var str3 = 'Test \n str is no good!'; var str4 = 'final test'; document.write(replaceReg(reg,str)+'<br />'); document.write(replaceReg(reg,str2)+'<br />'); document.write(replaceReg(reg,str3)+'<br />'); document.write(replaceReg(reg,str4)+'<br />'); </script>
以下只首字母大寫,其它字母大小寫不作處理
<script language="JavaScript"> <!-- var str="xi nAn shi you xUe yuan china people" alert(str.replace(/\s[a-z]/g,function($1){return $1.toLocaleUpperCase()}).replace(/^[a- z]/,function($1){return $1.toLocaleUpperCase()})) //--> </script>
運行代碼,直接看效果就可以了!