如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
目前投票的答案是正确的,但它不会在资本化第一个字符之前切断或检查链条的长度。
String.prototype.ucfirst = function(notrim) {
s = notrim ? this : this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'').replace(/\s+/g,' ');
return s.length > 0 ? s.charAt(0).toUpperCase() + s.slice(1) : s;
}
设置 notrim 论点,以防止第一条线被推翻:
'pizza'.ucfirst() => 'Pizza'
' pizza'.ucfirst() => 'Pizza'
' pizza'.ucfirst(true) => ' pizza'
其他回答
每个链条的第一个字符都被资本化了。
函数资本化(词){返回词[0].toUpperCase() + word.slice(1).toLowerCase(); } console.log(capitalize(“john”)); //John console.log(capitalize(“BRAVO”)); //Bravo console.log(capitalize(“BLAne”)); //Blane
有一个非常简单的方式来实现它通过替代。
'foo'.replace(/^./, str => str.toUpperCase())
结果:
'Foo'
关于TypeScript
capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
/*
* As terse as possible, assuming you're using ES version 6+
*/
var upLetter1=s=>s.replace(/./,m=>m.toUpperCase());
console.log(upLetter1("the quick brown fox jumped over the lazy dog."));
//\\ The quick brown fox jumped over the lazy dog. //\\
string = string.replace(string.charAt(0), string.charAt(0).toUpperCase());