如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
这个解决方案可能是新的,也许是最简单的。
函数第一UpperCase(输入) {返回输入[0].toUpperCase() + input.substr(1); } console.log(第一UpperCase(“资本化第一字母”));
其他回答
function capitalize(s) {
// returns the first letter capitalized + the string from index 1 and out aka. the rest of the string
return s[0].toUpperCase() + s.substr(1);
}
// examples
capitalize('this is a test');
=> 'This is a test'
capitalize('the Eiffel Tower');
=> 'The Eiffel Tower'
capitalize('/index.html');
=> '/index.html'
在这里,单行代码存档字母第一字母资本使用JS
yourstring?.charAt(0)?.toUpperCase() + yourstring?.slice(1).toLocaleLowerCase()
我在我的开发环境中使用这些线路,特别是当我与HTTP等API合作时:
假设您有一个 HTTP 标题,您希望在其名义中资本化每个初始字母,并在其组成词之间添加混合物。
'access control allow origin'
.replace(/\b\w/g, function (match) {
return match.toUpperCase();
})
.split(' ')
.join('-');
// Output: 'Access-Control-Allow-Origin'
这可能不是最优雅和最有吸引力的功能定义,但它肯定会完成工作。
我們可以獲得第一個角色與我最喜歡的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();
});
};
下面是最受欢迎的答案的简短版本,通过将线作为序列来处理第一个字母:
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)) || ""