2015-08-17 19 views
1

我想修改一个现有的JavaScript函数,通过将第一个字母的第一个字母设置为大写,正确地格式化用户名,以及最后一个名字名称。大写的情况下,当有一个短划线之间的姓氏

但是也有一些连字符,当这些发生的时候,看起来就像雨果Bearsotti-potz,而实际上它应该是雨果Bearsotti-Potz一些姓氏

我想寻求帮助,以修改该功能所以如果可能的话,它允许适当的情况下使用连字符连字符。

下面是现有的代码(相关片段只):

 if (input) { 
      var out = ''; 
      input.split(delimiter || ' ').forEach(function (sector) { 
       var x = sector.toLowerCase(); 
       out += x.charAt(0).toUpperCase() + x.substr(1) + ' '; 
      }); 
      if (out.length > 0) { 
       out = out.substring(0, out.length - 1); 
      } 
      return out; 
     } 

非常感谢。

回答

1

你也可以创建一个功能用于在任何给定分隔符后大写第一个字符。虽然不像正则表达式解决方案那么简洁。

function capitalizeAfter(input, delimiter) { 
    var output = '', 
     pieces = input.split(delimiter); 

    pieces.forEach(function(section, index) { 
    // capitalize the first character and add the remaining section back 
    output += section[0].toUpperCase() + section.substr(1); 

    // add the delimiter back if it isn't the last section 
    if (index !== pieces.length - 1) { 
     output += delimiter; 
    } 
    } 
    return output; 
} 

然后,它会被用于像这样:

if (input) { 
    return capitalizeAfter(capitalizeAfter(input.toLowerCase(), ' '), '-'); 
} 
+0

这是一个很好的例子。谢谢csbarnes :) –

2

这应该满足你的测试条件设置:http://plnkr.co/edit/9welW6?p=preview

HTML:

<input type="text" ng-model="foo"> 
<br> 
{{foo | nameCaps}} 

JS:

app.filter('nameCaps',function(){ 
    return function(input) { 
    if (!input) return; 
    return input.toString().replace(/\b([a-z])/g, function(ch) { 
     return ch.toUpperCase(); 
    }); 
    }; 
}); 

虽然我警惕,作出关于人的名字假设http://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/

+0

'\ B'是 “字边界” 选择器。非常方便http://www.regular-expressions.info/wordboundaries.html – wesww

相关问题