使用角度js将首字母和字母后跟一个点(。)大写

时间:2017-01-04 12:55:21

标签: javascript angularjs

我需要将字符串中的第一个字母大写, 例如,

 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);
            }
        }
    });

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:-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)
            }
        }
    });