如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
咖啡文字
ucfirst = (str) -> str.charAt(0).toUpperCase() + str.slice(1)
作为一个严格的原型方法:
String::capitalize = -> @charAt(0).toUpperCase() + @slice(1)
其他回答
ucfirst函数工作,如果你这样做。
function ucfirst(str) {
var firstLetter = str.slice(0,1);
return firstLetter.toUpperCase() + str.substring(1);
}
谢谢JP的解释。
优雅
const capitalize = ([firstChar, ...rest]) => `${firstChar.toUpperCase()}${rest.join('')}`;
您可以使用 regex 方法:
str.replace(/(^|\s)\S/g, letter => letter.toUpperCase());
/*
* 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.prototype: