如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?

例如:

“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”


当前回答

看看这个解决方案:

var stringVal = 'master';
stringVal.replace(/^./, stringVal[0].toUpperCase()); // Returns Master

其他回答

var capitalized = yourstring[0].toUpperCase() + yourstring.substr(1);

下面是最受欢迎的答案的简短版本,通过将线作为序列来处理第一个字母:

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)) || ""

你应该这样做:

let text = "lower case";
text = text.charAt(0).toUpperCase() + text.substring(1, text.length);

在CSS中:

p::first-letter {
    text-transform:capitalize;
}

这就是同样的行动:

var newStr = string.slice(0,1).toUpperCase() + string.slice(1);