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

例如:

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


当前回答

您可以使用 String#chatAt 获取第一个字符,将其转向上方,然后将其与链条的剩余部分相结合。

function capitalizeFirstLetter(v) {
  return v.charAt(0).toUpperCase() + v.substring(1);
}

其他回答

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

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

一条线路:

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

适用于所有 Unicode 字符的解决方案

57 81 不同答案这个问题,一些离主题,但其中没有一个提出重要问题,没有一个列出的解决方案将与亚洲字符, emoji,和其他高 Unicode 点值字符在许多浏览器工作。

const consistantCapitalizeFirstLetter = "\uD852\uDF62".length === 1 ?
    function(S) {
        "use-strict"; // Hooray! The browser uses UTF-32!
        return S.charAt(0).toUpperCase() + S.substring(1);
    } : function(S) {
        "use-strict";
        // The browser is using UCS16 to store UTF-16
        var code = S.charCodeAt(0)|0;
        return (
          code >= 0xD800 && code <= 0xDBFF ? // Detect surrogate pair
            S.slice(0,2).toUpperCase() + S.substring(2) :
            S.charAt(0).toUpperCase() + S.substring(1)
        );
    };
const prettyCapitalizeFirstLetter = "\uD852\uDF62".length === 1 ?
    function(S) {
        "use-strict"; // Hooray! The browser uses UTF-32!
        return S.charAt(0).toLocaleUpperCase() + S.substring(1);
    } : function(S) {
        "use-strict";
        // The browser is using UCS16 to store UTF-16
        var code = S.charCodeAt(0)|0;
        return (
          code >= 0xD800 && code <= 0xDBFF ? // Detect surrogate pair
            S.slice(0,2).toLocaleUpperCase() + S.substring(2) :
            S.charAt(0).toLocaleUpperCase() + S.substring(1)
        );
    };

请注意,上述解决方案试图计算 UTF-32. 然而,规格正式表示,浏览器必须在 UTF-16 地图中完成一切。 然而,如果我们都聚集在一起,做我们的部分,并开始为 UTF32 做好准备,那么 TC39 可能会允许浏览器开始使用 UTF-32 (就像 Python 如何使用 24 位字符的每个字符一样)

最短的 3 个解决方案, 1 和 2 处理 s 行是 “”, null 和 undefined 的情况:

 s&&s[0].toUpperCase()+s.slice(1)        // 32 char

 s&&s.replace(/./,s[0].toUpperCase())    // 36 char - using regexp

'foo'.replace(/./,x=>x.toUpperCase())    // 31 char - direct on string, ES6

s=‘foo bar’; console.log( s&&s[0].toUpperCase()+s.slice(1) ); console.log( s&s.replace(/./,s[0].toUpperCase()); console.log( 'foo bar'.replace(/./,x=>x.toUpperCase()) );

function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}

一些其他答案修改 String.prototype(这个答案也被用来),但我会建议反对这一点现在由于可持续性(很难找到函数在哪里被添加到原型,如果另一个代码使用相同的名称 / 一个浏览器添加一个原始函数与相同的名称在未来可能导致冲突)。