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

例如:

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


当前回答

您可以使用下面的常规表达式:

return string1.toLowerCase().replace(/^[a-zA-z]|\s(.)/ig, L => L.toUpperCase());

其他回答

发表一个编辑 @salim 的答案,包括本地字母转换。

var str = "test string";
str = str.substring(0,1).toLocaleUpperCase() + str.substring(1);
var capitalized = yourstring[0].toUpperCase() + yourstring.substr(1);

如果你想在一行中资本化每个第一封信,例如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");

使用原型

String.prototype.capitalize = function () {
    return this.charAt(0) + this.slice(1).toLowerCase();
  }

或使用功能

function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
}
function capitalize(string) {
    return string.replace(/^./, Function.call.bind("".toUpperCase));
}