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

例如:

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


当前回答

yourString.replace(/^[a-z]/, function(m){ return m.toUpperCase() });

(您可以将其嵌入到函数中,或者甚至将其添加到 String 原型中,如果您经常使用它。

其他回答

下面有一个函数称为ucfirst((缩写为“上例第一字母”):

function ucfirst(str) {
    var firstLetter = str.substr(0, 1);
    return firstLetter.toUpperCase() + str.substr(1);
}

您可以通过称 ucfirst(“某些链条”)来资本化一个链条 - 例如,

ucfirst("this is a test") --> "This is a test"

在第一行中,它提取第一Letter,然后在第二行中,它通过呼叫第一Letter.toUpperCase()来资本化第一Letter,并将其与其余的行列相结合,这是通过呼叫str.substr(1)来找到的。

你可能认为这会失败一个空的线条,而且实际上在一个语言如C,你会不得不为此加密,但是在JavaScript中,当你采取一个空的线条,你只是得到一个空的线条。

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

以下是基于此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);
}

此分類上一篇

/*
 * As terse as possible, assuming you're using ES version 6+
 */
var upLetter1=s=>s.replace(/./,m=>m.toUpperCase());

console.log(upLetter1("the quick brown fox jumped over the lazy dog."));
//\\ The quick brown fox jumped over the lazy dog. //\\

如果您已经(或正在考虑)使用Lodash,解决方案很容易:

_.upperFirst('fred');
// => 'Fred'

_.upperFirst('FRED');
// => 'FRED'

_.capitalize('fred') //=> 'Fred'

查看他们的文档: https://lodash.com/docs#capitalize

_.camelCase(“Foo Bar”); //=>“FooBar”

https://lodash.com/docs/4.15.0#camelCase

_.lowerFirst('Fred');
// => 'fred'

_.lowerFirst('FRED');
// => 'fRED'

_.snakeCase('Foo Bar');
// => 'foo_bar'

Vanilla JavaScript for first up 案例:

function upperCaseFirst(str){
    return str.charAt(0).toUpperCase() + str.substring(1);
}

此分類上一篇: I like this one:

yourString.replace(/(^[a-z])/i, (str, firstLetter) => firstLetter.toUpperCase())