如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
您可以使用 String#chatAt 获取第一个字符,将其转向上方,然后将其与链条的剩余部分相结合。
function capitalizeFirstLetter(v) {
return v.charAt(0).toUpperCase() + v.substring(1);
}
其他回答
在CSS中:
p::first-letter {
text-transform:capitalize;
}
这就是同样的行动:
var newStr = string.slice(0,1).toUpperCase() + string.slice(1);
我們可以獲得第一個角色與我最喜歡的RegExp之一,看起來像一個可愛的微笑: /^./
String.prototype.capitalize = function () {
return this.replace(/^./, function (match) {
return match.toUpperCase();
});
};
对于所有咖啡豆:
String::capitalize = ->
@replace /^./, (match) ->
match.toUpperCase()
...和所有认为有更好的方式做到这一点的男孩,没有扩展原生原型:
var capitalize = function (input) {
return input.replace(/^./, function (match) {
return match.toUpperCase();
});
};
已经有这么多好答案,但你也可以使用一个简单的CSS转换:
text-transform: capitalize;
div.text-capitalize { 文本转型:资本化; } <h2>文本转型:资本化:</h2> <div class="text-capitalize">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
关于TypeScript
capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}