[英]upper case both last name when there is a dash in between
我想修改現有的JavaScript函數,通過將名字的首字母設置為大寫以及姓氏的名字來正確格式化用戶名。
有一些帶有連字符的姓氏,當它們發生時,它們看起來像Hugo Bearsotti-potz,而實際上應該是Hugo 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;
}
非常感謝。
這應該滿足您設置的測試條件: 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();
});
};
});
盡管我對假設人們的名字持謹慎態度,但仍對此不抱懷疑。
您還可以創建一個函數,以在任何給定的定界符之后將第一個字符大寫。 雖然不如正則表達式解決方案那么簡潔。
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(), ' '), '-');
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.