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

例如:

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


当前回答

我只会用一个常见的表达式:

myString = '    the quick green alligator...';
myString.trim().replace(/^\w/, (c) => c.toUpperCase());

其他回答

let capitalize = (strPara)=>{
    let arr = Array.from(strPara);
    arr[0] = arr[0].toUpperCase();
    return arr.join("");
}

let str = capitalize("this is a test");
console.log(str);

这就是同样的行动:

var newStr = string.slice(0,1).toUpperCase() + string.slice(1);

最简单的解决方案是:

let yourSentence = 'it needs first letter upper case';

yourSentence.charAt(0).toUpperCase() + yourSentence.substr(1);

或:

yourSentence.charAt(0).toUpperCase() + yourSentence.slice(1);

或:

yourSentence.substr(0, 1).toUpperCase() + yourSentence.substr(1);

首頁 〉外文書 〉文學 〉文學 〉Capitalize First Word: Shortest

text.replace(/(^.)/, m => m.toUpperCase())

每一个字:最短

text.replace(/(^\w|\s\w)/g, m => m.toUpperCase());

如果你想确保剩下的在底部:

text.replace(/(^\w|\s\w)(\S*)/g, (_,m1,m2) => m1.toUpperCase()+m2.toLowerCase())

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

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

此分類上一篇