如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
最短的 3 个解决方案, 1 和 2 处理 s 行是 “”, null 和 undefined 的情况:
s&&s[0].toUpperCase()+s.slice(1) // 32 char
s&&s.replace(/./,s[0].toUpperCase()) // 36 char - using regexp
'foo'.replace(/./,x=>x.toUpperCase()) // 31 char - direct on string, ES6
s=‘foo bar’; console.log( s&&s[0].toUpperCase()+s.slice(1) ); console.log( s&s.replace(/./,s[0].toUpperCase()); console.log( 'foo bar'.replace(/./,x=>x.toUpperCase()) );
其他回答
一个简单的,紧凑的功能,将完成你的工作:
const capitalize = str => str.split(' ').map(sub => sub.charAt(0).toUpperCase() + sub.slice(1)).join(' ');
“Foo” > “Foo” “Foo Bar” > “Foo Bar”
yourString.replace(/^[a-z]/, function(m){ return m.toUpperCase() });
(您可以将其嵌入到函数中,或者甚至将其添加到 String 原型中,如果您经常使用它。
一条线(“输入线可以设置到任何条线”):
inputString.replace(/.{1}/, inputString.charAt(0).toUpperCase())
看看这个解决方案:
var stringVal = 'master';
stringVal.replace(/^./, stringVal[0].toUpperCase()); // Returns Master
一个小改进 - 每个字在标题。
String.prototype.toTitleCase = function(){
return this.replace(/\b(\w+)/g, function(m,p){ return p[0].toUpperCase() + p.substr(1).toLowerCase() });
}
var s = 'heLLo, wOrLD!';
console.log(s.toTitleCase()); // Hello, World!