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

例如:

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


当前回答

我在我的开发环境中使用这些线路,特别是当我与HTTP等API合作时:

假设您有一个 HTTP 标题,您希望在其名义中资本化每个初始字母,并在其组成词之间添加混合物。

'access control allow origin'
    .replace(/\b\w/g, function (match) {
        return match.toUpperCase();
    })
    .split(' ')
    .join('-');

// Output: 'Access-Control-Allow-Origin'

这可能不是最优雅和最有吸引力的功能定义,但它肯定会完成工作。

其他回答

这里是我的尝试,使一个普遍的功能,只有第一字母,或每个字母的第一字母,包括单词分开的单词(如一些第一名在法语)。

默认情况下,该函数仅将第一个字母归功,其余的字母无触。

参数:

lc: 忠于强迫下载的所有字(s): 忠于资本化每一个字

 

if( typeof String.prototype.capitalize !== "function" ) {
    String.prototype.capitalize = function( lc, all ) {
        if( all ) {
            return this.split( " " )
                       .map( currentValue => currentValue.capitalize( lc ), this )
                       .join( " " )
                       .split( "-" )
                       .map( currentValue => currentValue.capitalize( false ), this )
                       .join( "-" );
        } else {
            return lc
            ? this.charAt( 0 ).toUpperCase() + this.slice( 1 ).toLowerCase()
            : this.charAt( 0 ).toUpperCase() + this.slice( 1 );
        }
    }
}

如果您对发布的几种不同的方法的性能感兴趣:

以下是基于此JSperf测试的最快方法(从最快到最慢的订单)。

正如你可以看到的那样,前两种方法在性能方面基本上是相似的,而改变 String.prototype 则在性能方面是最慢的。

// 10,889,187 operations/sec
function capitalizeFirstLetter(string) {
    return string[0].toUpperCase() + string.slice(1);
}

// 10,875,535 operations/sec
function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}

// 4,632,536 operations/sec
function capitalizeFirstLetter(string) {
    return string.replace(/^./, string[0].toUpperCase());
}

// 1,977,828 operations/sec
String.prototype.capitalizeFirstLetter = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}

此分類上一篇

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

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

只是因为你可以,这并不意味着你应该,但是. 它需要 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("");
};

咖啡文字

ucfirst = (str) -> str.charAt(0).toUpperCase() + str.slice(1)

作为一个严格的原型方法:

String::capitalize = -> @charAt(0).toUpperCase() + @slice(1)