Home > Web Front-end > JS Tutorial > JavaScript implements capitalization of English initial letters_javascript skills

JavaScript implements capitalization of English initial letters_javascript skills

WBOY
Release: 2016-05-16 16:02:31
Original
1575 people have browsed it

Method 1:

function replaceStr(str){ // 正则法
 str = str.toLowerCase();
 var reg = /\b(\w)|\s(\w)/g; //  \b判断边界\s判断空格
 return str.replace(reg,function(m){ 
  return m.toUpperCase()
 });
}

function replaceStr1(str){
 str = str.toLowerCase();
 var strTemp = ""; //新字符串
 for(var i=0;i<str.length;i++){
  if(i == 0){
   strTemp += str[i].toUpperCase(); //第一个
   continue;
  }
  if(str[i] == " " && i< str.length-1){ //空格后
   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
Copy after login

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>


Copy after login

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>

Copy after login

CSS to implement:

<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>
Copy after login

The above is a summary of 4 ways to capitalize English initials. I hope you will like it.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template