我想修改现有的JavaScript函数,通过将名字首字母设置为大写字母以及姓氏的名字来正确格式化用户名。
有一些姓氏连字符,当这些名字发生时,它们看起来像Hugo Bearsotti-potz,实际上它应该是Hugo Bearsotti-Potz
我想请求帮助来修改此功能,以便在可能的情况下允许使用带连字符的姓氏。
以下是现有代码(仅限相关代码段):
#include <cstdint>
#include <iostream>
int
main(int, char *[])
{
// use uintmax_t and hope that the number still fits.
uintmax_t = 13ul; // or whatever
for (unsigned k = 1u;; ++k) {
// k is the number of digits
for (unsigned m = 1u; m <= k; ++m) {
// m is the number of 4s.
// We start at one 4 (zero does not make sense)
uintmax_t C = 0u;
// build C, add as many 4s as requested and
// fill up with zeros
for (unsigned i = 0; i < k; ++i) {
if (i < m) {
C = C * 10 + 4;
} else {
C = C * 10;
}
}
// check if we have a multiple of A
if (C % A == 0) {
std::cout << "C = " << C << std::endl;
std::cout << "B = " << (C / A) << std::endl;
return 0;
}
}
}
return 1;
}
非常感谢。
答案 0 :(得分: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/
的假设持谨慎态度答案 1 :(得分: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(), ' '), '-');
}