javascript capitalizes the first letter

  • 2020-06-01 08:14:50
  • OfStack

Method 1:


function replaceStr(str){ //  The regular method 
 str = str.toLowerCase();
 var reg = /\b(\w)|\s(\w)/g; //  \b Determine the boundary \s Determine the blank space 
 return str.replace(reg,function(m){ 
  return m.toUpperCase()
 });
}

function replaceStr1(str){
 str = str.toLowerCase();
 var strTemp = ""; // A new string 
 for(var i=0;i<str.length;i++){
  if(i == 0){
   strTemp += str[i].toUpperCase(); // The first 1 a 
   continue;
  }
  if(str[i] == " " && i< str.length-1){ // After the space 
   strTemp += " ";
   strTemp += str[i+1].toUpperCase();
   i++;
   continue;
  }
  strTemp += str[i];
 }
  return strTemp;
 }
 

var text = "abcd ABCD efGH";
console.log(replaceStr(text));//Abcd Abcd Efgh
console.log(replaceStr1(text));//Abcd Abcd Efgh

Method 2:


<script type="text\javascript">
function ucfirst(str){
var str = str.toLowerCase();
var strarr = str.split(' ');
var result = '';
for(var i in strarr){
result += strarr[i].substring(0,1).toUpperCase()+strarr[i].substring(1)+' ';
}
return result;
}
</script>


Method 3:


<script type="text\javascript">
function ucfirst(str) {
var str = str.toLowerCase();
str = str.replace(/\b\w+\b/g, function(word){
  return word.substring(0,1).toUpperCase()+word.substring(1);
});
return str; 
</script>

CSS to achieve:


<html>
 <head>
 <style type="text/css"> 
  h1 {text-transform: uppercase} 
  p.uppercase {text-transform: uppercase}   
  p.lowercase {text-transform: lowercase}  
  p.capitalize {text-transform: capitalize } 
 </style>
 </head>
 <body>
  <h1>This Is An H1 Element</h1>
   <p class="uppercase">This is a test.</p><p class="lowercase">This is a test.</p><p class="capitalize">This is a test.</p>
 </body>
</html>

The above is to give you a summary of the four ways to achieve English capital letters, I hope you will like it.


Related articles: