如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
你可以做 str.replace(str[0], str[0].toUpperCase())。
看看这个例子:
let str = “Hello, WORLD!” let newStr = str.replace(str[0], str[0].toUpperCase()) console.log(“str:”, str) console.log(“newStr:”, newStr)
其他回答
下面是更以对象为导向的方法:
Object.defineProperty(String.prototype, 'capitalize', {
value: function() {
return this.charAt(0).toUpperCase() + this.slice(1);
},
enumerable: false
});
你会称之为这个功能,如下:
"hello, world!".capitalize();
预计产量是:
"Hello, world!"
看看这个解决方案:
var stringVal = 'master';
stringVal.replace(/^./, stringVal[0].toUpperCase()); // Returns Master
咖啡文字
ucfirst = (str) -> str.charAt(0).toUpperCase() + str.slice(1)
作为一个严格的原型方法:
String::capitalize = -> @charAt(0).toUpperCase() + @slice(1)
这就是同样的行动:
var newStr = string.slice(0,1).toUpperCase() + string.slice(1);
或者你可以使用Sugar.js资本()
例子:
'hello'.capitalize() -> 'Hello'
'hello kitty'.capitalize() -> 'Hello kitty'
'hello kitty'.capitalize(true) -> 'Hello Kitty'