如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
功能性方法
const capitalize = ([s, ...tring]) =>
[s.toUpperCase(), ...tring]
.join('');
然后你可以
const titleCase = str =>
str
.split(' ')
.map(capitalize)
.join(' ')
其他回答
尝试下列功能:
function capitalize (string) {
return [].map.call(string, (char, i) => i ? char : char.toUpperCase()).join('')
}
使用:
capitalize('hello, world!')
结果:
Hello, world!
这个解决方案可能是新的,也许是最简单的。
函数第一UpperCase(输入) {返回输入[0].toUpperCase() + input.substr(1); } console.log(第一UpperCase(“资本化第一字母”));
使用原型
String.prototype.capitalize = function () {
return this.charAt(0) + this.slice(1).toLowerCase();
}
或使用功能
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
}
String.prototype.capitalize = function(){
return this.replace(/(^|\s)([a-z])/g,
function(m, p1, p2) {
return p1 + p2.toUpperCase();
});
};
使用:
capitalizedString = someString.capitalize();
此分類上一篇: This Is a Text String
如果您已经(或正在考虑)使用Lodash,解决方案很容易:
_.upperFirst('fred');
// => 'Fred'
_.upperFirst('FRED');
// => 'FRED'
_.capitalize('fred') //=> 'Fred'
查看他们的文档: https://lodash.com/docs#capitalize
_.camelCase(“Foo Bar”); //=>“FooBar”
https://lodash.com/docs/4.15.0#camelCase
_.lowerFirst('Fred');
// => 'fred'
_.lowerFirst('FRED');
// => 'fRED'
_.snakeCase('Foo Bar');
// => 'foo_bar'
Vanilla JavaScript for first up 案例:
function upperCaseFirst(str){
return str.charAt(0).toUpperCase() + str.substring(1);
}