2017-01-04 34 views
-6

我需要首字母大寫在一個字符串, 例如,首字母大寫和字母后跟一個句點(。),使用角JS

sumo => Sumo 

,並且還需要利用與串以下格式,

Dr.ravi kumar => Dr.Ravi kumar 

我使用的角度濾波器,這對於第一條件工作良好,但它不用於第二個工作,這是我使用的過濾器,

angular 
    .module('app') 
    .filter('capitalize', function() { 
     return function (input, scope) { 
      if (input != null) { 
       input = input.toLowerCase(); 
       return input.substring(0, 1).toUpperCase() + input.substring(1); 
      } 
     } 
    }); 
+0

你可以用點分割字符串 「」並將兩個字符串的首字母大寫。 –

+0

上面的代碼如何能夠大寫'sumo joe'的'j'? – jensgram

+1

你甚至試過尋找這個嗎? – charlietfl

回答

-1

試試這個:

angular 
    .module('app') 
    .filter('capitalize', function() { 
     return function (input, scope) { 
      if (input != null) { 
       input = input.toLowerCase(); 
       return input.substring(0, 1).toUpperCase() +input.substring(1).split('.')[0] + '.' + input.substring(1).split('.')[1].substring(0, 1).toUpperCase() + input.substring(1).split('.')[1].substring(1) 
      } 
     } 
    }); 
+0

它將單詞後面跟着點(。)轉換爲大寫,例如,dr.ravi => Dr.RAVI – durai

+0

你可以再次檢查,它是根據你的期望返回的,例如。 dr.ravi => Dr.Ravi – CommonPlane

0
string="hi you. im dr.test. nice to see you. by the way... what was your name?"; 
string=string.split(""); 
up=true; 
for(key in string){ 
console.log(string[key],up); 
    if(string[key]==="."){ 
    up=true; 
    }else{ 
    if(up&&(string[key]!==" ")){ 
    string[key]=string[key].toUpperCase(); 
    up=false; 
    }}} 
    string=string.join(""); 
console.log('result:',string); 

我原來的答覆(慢):

string="hi you. im dr.test. nice to see you"; 
words=string.split(" "); 
var dots=[0]; 
for(key in words){//loop trough words 
    var word=words[key]; 
    var chars=word.split(""); 
    if(dots.length){//there was a dot before, that wasnt a doctor: lets find the first letter +upper 
     chars[0]=chars[0].toUpperCase(); 
     dots.shift();//remove dot  
    } 
    chars.forEach((char,i)=>{if(char=="."){dots.push(i)}}); 
    if(dots[0]&&dots[0]!=chars.length-1){//dot not at the end... 
     chars[dots[0]+1]=chars[dots[0]+1].toUpperCase();//upper our doctor... 
     dots.shift();//remove dot from array 
    } 
    word=chars.join(""); 
    words[key]=word; 
} 
string=words.join(" "); 
console.log('result:',string); 

工作例如: http://jsbin.com/docecuvote/edit?console