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

例如:

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


当前回答

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

其他回答

如果您使用 Underscore.js 或 Lodash, underscore.string 图书馆提供链接扩展,包括资本化:

_.capitalize(string) 将序列的第一字母转换为顶端。

例子:

_.capitalize("foo bar") == "Foo bar"

一条线路:

此分類上一篇: 重定向,重定向,重定向,重定向,重定向

你可以做 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)

使用:

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

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

只是因为你可以,这并不意味着你应该,但是. 它需要 ECMAScript 6 因为代码使用序列破坏。

const capitalizeFirstLetter = s => {
  const type = typeof s;
  if (type !== "string") {
    throw new Error(`Expected string, instead received ${type}`);
  }

  const [firstChar, ...remainingChars] = s;

  return [firstChar.toUpperCase(), ...remainingChars].join("");
};