JS 将一段文本 每个英文首字母大写

 1 function replaceStr(str){ // 正则法
 2   str = str.toLowerCase();
 3   var reg = /\b(\w)|\s(\w)/g; //   \b判断边界\s判断空格
 4   return str.replace(reg,function(m){ 
 5     return m.toUpperCase()
 6   });
 7 }
 8 
 9 function replaceStr1(str){
10   str = str.toLowerCase();
11   var strTemp = "";  //新字符串
12   for(var i=0;i<str.length;i++){
13     if(i == 0){
14       strTemp += str[i].toUpperCase(); //第一个
15       continue;
16     }
17     if(str[i] == " " && i< str.length-1){ //空格后
18       strTemp += " ";
19       strTemp += str[i+1].toUpperCase();
20       i++;
21       continue;
22     }
23     strTemp += str[i];
24   }
25     return strTemp;
26   }
27   
28 
29 var text = "abcd ABCD efGH";
30 console.log(replaceStr(text));//Abcd Abcd Efgh
31 console.log(replaceStr1(text));//Abcd Abcd Efgh

 

posted @ 2015-04-09 19:40  -渔人码头-  阅读(1198)  评论(0编辑  收藏  举报