如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
你应该这样做:
let text = "lower case";
text = text.charAt(0).toUpperCase() + text.substring(1, text.length);
其他回答
我们将使用CSS来实现这一点,它也可以从外部CSS设置。
<span text-transform="capitalize ">The first letter of each word becomes an upper case</span>
使用Vanilla JavaScript,我们可以:
let string = "test case"
string = string[0].toUpperCase() + string.substring(1)
//return "Test case"
此分類上一篇:</b/>
字符串[0].toUpperCase():将字符串中的第一个字符转换为顶部字符串
string.substring(1):在行中删除第一个字母并返回剩余的字符
text-transform="capitalize":在这个标签的顶部字母中创建每个字母的第一个字母. 如果您使用“uppercase”作为文本转换的值,标签中的每个字母将是一个字母。
下面是更以对象为导向的方法:
Object.defineProperty(String.prototype, 'capitalize', {
value: function() {
return this.charAt(0).toUpperCase() + this.slice(1);
},
enumerable: false
});
你会称之为这个功能,如下:
"hello, world!".capitalize();
预计产量是:
"Hello, world!"
下面是最受欢迎的答案的简短版本,通过将线作为序列来处理第一个字母:
function capitalize(s)
{
return s[0].toUpperCase() + s.slice(1);
}
更新
根据下面的评论,这在 IE 7 或下方不起作用。
更新2:
要避免未定义为空线(参见 @njzk2 下面的评论),您可以检查一个空线:
function capitalize(s)
{
return s && s[0].toUpperCase() + s.slice(1);
}
是版本
const capitalize = s => s && s[0].toUpperCase() + s.slice(1)
// to always return type string event when s may be falsy other than empty-string
const capitalize = s => (s && s[0].toUpperCase() + s.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();
});
};
yourString.replace(/^[a-z]/, function(m){ return m.toUpperCase() });
(您可以将其嵌入到函数中,或者甚至将其添加到 String 原型中,如果您经常使用它。