如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
你应该这样做:
let text = "lower case";
text = text.charAt(0).toUpperCase() + text.substring(1, text.length);
其他回答
第一封信与验证的资本化
function capitalizeFirstLetter(str) {
return (str && typeof str === 'string') ? (str.charAt(0).toUpperCase() + str.slice(1)) : "";
}
测试
console.log(capitalizeFirstLetter(0)); // Output: ""
console.log(capitalizeFirstLetter(null)); // Output: ""
console.log(capitalizeFirstLetter("test")); // Output: "Test"
console.log(capitalizeFirstLetter({})); // Output: ""
下面是更以对象为导向的方法:
Object.defineProperty(String.prototype, 'capitalize', {
value: function() {
return this.charAt(0).toUpperCase() + this.slice(1);
},
enumerable: false
});
你会称之为这个功能,如下:
"hello, world!".capitalize();
预计产量是:
"Hello, world!"
我們可以獲得第一個角色與我最喜歡的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();
});
};
使用原型
String.prototype.capitalize = function () {
return this.charAt(0) + this.slice(1).toLowerCase();
}
或使用功能
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
}
使用:
var str = “ruby java”; console.log(str.charAt(0).toUpperCase() + str.substring(1));
它将输出“Ruby java”到控制台。