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

例如:

“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/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)) || ""

其他回答

如果你去其中一个 regex 答案,请记住,它们只会与 ASCII 字符一起工作. 所有的 Unicode 字母都不会被打破. XRegExp 图书馆和其 Unicode 插件解决这个问题,如果你想与 regex 保持。

String.prototype.capitalize = function () {
    return this.replace(XRegExp("^\\p{L}"), function ($0) { return $0.toUpperCase(); })
}

考虑到它仍然不涵盖所有可能性(混合字符,见 http://www.regular-expressions.info/unicode.html),似乎更容易使用.charAt(0).toUpperCase() 方法。

这是一个简单的

const upper = lower.replace(/^\w/, c => c.toUpperCase());
s[0].toUpperCase``+s.substr`1`

let s = 'hello there' console.log( s[0].toUpperCase''+s.substr`1` )

该方法将采取一个值,然后将其分成一系列的线条。

const firstLetterToUpperCase = value => {
 return value.replace(
    value.split("")["0"], // Split stirng and get the first letter 
    value
        .split("")
        ["0"].toString()
        .toUpperCase() // Split string and get the first letter to replace it with an uppercase value
  );
};

使用 JS 取代字符串方法 & 一个常见的表达 w/ 一个词界限似乎很简单。

首頁 〉外文書 〉文學 〉西洋文學 〉Capitalize the first words' first character: "the Eiffel Tower" --> "The Eiffel Tower"

str.replace(/\b\w/, v => v.toUpperCase())

首頁 〉外文書 〉文學 〉西洋文學 〉Capitalize all words' first character: "the Eiffel Tower" --> "The Eiffel Tower"

str.replace(/\b\w/g, v => v.toUpperCase())