JS USES the regular expression conversion case example

  • 2020-03-30 03:57:31
  • OfStack

Js application of regular expression conversion case, the code is very simple, look at the code:

The following letters are uppercase and lowercase


<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>

The following letters are capitalized, and the rest are not capitalized


<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>

Run the code, see the effect directly can!


Related articles: