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

例如:

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


当前回答

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

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

其他回答

这样做的一个简单的方式是:

如果您想将其添加到 String.prototype:

var str = "test string";
str = str.substring(0,1).toUpperCase() + str.substring(1);

一个小改进 - 每个字在标题。

String.prototype.toTitleCase = function(){
    return this.replace(/\b(\w+)/g, function(m,p){ return p[0].toUpperCase() + p.substr(1).toLowerCase() });
}

var s = 'heLLo, wOrLD!';
console.log(s.toTitleCase()); // Hello, World!
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'

使用:

var str = “ruby java”; console.log(str.charAt(0).toUpperCase() + str.substring(1));

它将输出“Ruby java”到控制台。