如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
这个代码在某些情况下可能工作得很好:
函数 capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1); } console.log(capitalizeFirstLetter('foo')); // Foo // 但如果我们有这样的它不会工作好 console.log(capitalizeFirstLetter('fOo')); // FOo
但是,如果你真的想确保,只有第一个字母被资本化,其余的字母是由下层字母构成的,你可以调整代码如下:
函数 capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase(); } console.log(capitalizeFirstLetter('fOo')); // Foo
其他回答
第一封信与验证的资本化
function capitalizeFirstLetter(str) {
return (str && typeof str === 'string') ? (str.charAt(0).toUpperCase() + str.slice(1)) : "";
}
测试
console.log(capitalizeFirstLetter(0)); // Output: ""
console.log(capitalizeFirstLetter(null)); // Output: ""
console.log(capitalizeFirstLetter("test")); // Output: "Test"
console.log(capitalizeFirstLetter({})); // Output: ""
如果您已经(或正在考虑)使用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);
}
将所有单词的第一字母分为一个字符串:
function ucFirstAllWords( str )
{
var pieces = str.split(" ");
for ( var i = 0; i < pieces.length; i++ )
{
var j = pieces[i].charAt(0).toUpperCase();
pieces[i] = j + pieces[i].substr(1);
}
return pieces.join(" ");
}
只是因为你可以,这并不意味着你应该,但是. 它需要 ECMAScript 6 因为代码使用序列破坏。
const capitalizeFirstLetter = s => {
const type = typeof s;
if (type !== "string") {
throw new Error(`Expected string, instead received ${type}`);
}
const [firstChar, ...remainingChars] = s;
return [firstChar.toUpperCase(), ...remainingChars].join("");
};
咖啡文字
ucfirst = (str) -> str.charAt(0).toUpperCase() + str.slice(1)
作为一个严格的原型方法:
String::capitalize = -> @charAt(0).toUpperCase() + @slice(1)