如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
/*
* 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. //\\
其他回答
我更喜欢使用一个以功能方式为导向的解决方案(例如地图序列):
Array.from(str).map((letter, i) => i === 0 ? letter.toUpperCase() : letter ).join('');
var a = "this is a test"
console.log(a.replace(/^[a-z]/g, txt => txt.toUpperCase()));
如果你需要所有的字母,从一个字母开始,你可以使用以下函数:
const capitalLetters = (s) => {
return s.trim().split(" ").map(i => i[0].toUpperCase() + i.substr(1)).reduce((ac, i) => `${ac} ${i}`);
}
例子:
console.log(`result: ${capitalLetters("this is a test")}`)
// Result: "This Is A Test"
string = string.replace(string.charAt(0), string.charAt(0).toUpperCase());
有一个非常简单的方式来实现它通过替代。
'foo'.replace(/^./, str => str.toUpperCase())
结果:
'Foo'