如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
每个链条的第一个字符都被资本化了。
函数资本化(词){返回词[0].toUpperCase() + word.slice(1).toLowerCase(); } console.log(capitalize(“john”)); //John console.log(capitalize(“BRAVO”)); //Bravo console.log(capitalize(“BLAne”)); //Blane
其他回答
有几种方法可以做到这一点,请尝试下面的
var lower = 'the Eiffel Tower';
var upper = lower.charAt(0).toUpperCase() + lower.substr(1);
如果你很舒服的常规表达,你会这样做:
var upper = lower.replace(/^\w/, function (chr) {
return chr.toUpperCase();
});
你甚至可以通过使用更现代化的合成来迈出一步:
const upper = lower.replace(/^\w/, c => c.toUpperCase());
此外,这也将照顾如示例中提到的负面场景,如从特殊字符开始的单词,如!@#$%^&*()}{{[];':",<>/?。
我最近在一个项目中需要类似的功能,这就是我如何实施它:
函数 capitlizeFirst(str) { // checks for null, undefined and empty string if (!str) return; return str.match("^[a-z]")? str.charAt(0).toUpperCase() + str.substring(1) : str; } console.log(capitlizeFirst("")); console.log(capitlizeFirst(null)); console.log(capitlizeFirst(undefined)); console.log(capitlizeFirst("hello world")); console.log(capitlizeFirst("/index.html"));
一条线(“输入线可以设置到任何条线”):
inputString.replace(/.{1}/, inputString.charAt(0).toUpperCase())
var capitalizeMe = "string not starting with capital"
资本化与substr
var capitalized = capitalizeMe.substr(0, 1).toUpperCase() + capitalizeMe.substr(1);
目前投票的答案是正确的,但它不会在资本化第一个字符之前切断或检查链条的长度。
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'