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

例如:

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


当前回答

string = string.replace(string.charAt(0), string.charAt(0).toUpperCase());

其他回答

如果你想在一行中资本化每个第一封信,例如Hello to the world,你可以使用以下(由史蒂夫·哈里森重复):

function capitalizeEveryFirstLetter(string) {
    var splitStr = string.split(' ')
    var fullStr = '';

    $.each(splitStr,function(index){
        var currentSplit = splitStr[index].charAt(0).toUpperCase() + splitStr[index].slice(1);
        fullStr += currentSplit + " "
    });

    return fullStr;
}

您可以通过使用以下方式呼叫:

capitalizeFirstLetter("hello to the world");
/*
 * As terse as possible, assuming you're using ES version 6+
 */
var upLetter1=s=>s.replace(/./,m=>m.toUpperCase());

console.log(upLetter1("the quick brown fox jumped over the lazy dog."));
//\\ The quick brown fox jumped over the lazy dog. //\\

如同它:

function capitalize(string,a) {
    var tempstr = string.toLowerCase();
    if (a == false || a == undefined)
        return tempstr.replace(tempstr[0], tempstr[0].toUpperCase());
    else {
        return tempstr.split(" ").map(function (i) { return i[0].toUpperCase() + i.substring(1) }).join(" ");
    }
}


capitalize('stack overflow yeah!',true)); //Stack Overflow Yeah!

capitalize('stack stack stack stack overflow yeah!'));//Stack overflow yeah!

https://jsfiddle.net/dgmLgv7b/

ucfirst函数工作,如果你这样做。

function ucfirst(str) {
    var firstLetter = str.slice(0,1);
    return firstLetter.toUpperCase() + str.substring(1);
}

谢谢JP的解释。

优雅

const capitalize = ([firstChar, ...rest]) => `${firstChar.toUpperCase()}${rest.join('')}`;