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

例如:

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


当前回答

使用 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())

其他回答

这是一个简单的

const upper = lower.replace(/^\w/, c => c.toUpperCase());

这个解决方案可能是新的,也许是最简单的。

函数第一UpperCase(输入) {返回输入[0].toUpperCase() + input.substr(1); } console.log(第一UpperCase(“资本化第一字母”));

一个小改进 - 每个字在标题。

String.prototype.toTitleCase = function(){
    return this.replace(/\b(\w+)/g, function(m,p){ return p[0].toUpperCase() + p.substr(1).toLowerCase() });
}

var s = 'heLLo, wOrLD!';
console.log(s.toTitleCase()); // Hello, World!

如果我可以稍微改变代码,我发现,如果我通过这个功能运行一条所有条线,什么都不会发生,所以......这里是我的条线。

String.prototype.capitalize = function(){
    return this.toLowerCase().replace( /(^|\s)([a-z])/g , function(m, p1, p2) {
        return p1 + p2.toUpperCase();
    });
}

只有CSS

如果转换仅需要在网页上显示:

p::first-letter {
  text-transform: uppercase;
}

尽管被称为“::第一字”,但它适用于第一个字符,即在 %a 字符的情况下,这个选择器将适用于 % 并且作为这样一个不会被资本化。

ES2015 单线

const capitalizeFirstChar = str => str.charAt(0).toUpperCase() + str.substring(1);

注意事项

在我所执行的指标中,在 string.charAt(0) 和 string(0) 之间没有显著的差异。 但是,请注意,该 string(0) 会为一个空的 string 不定义,因此该函数必须重写以使用“string && string(0)”,这与替代品相比是过于垂直的。

与 substring() 和 slice() 之间的比较

差异在今天相当微小(自己进行测试):

21,580,613.15 ops/s ±1.6% for substring(), 21,096,394.34 ops/s ±1.8% (2.24% 缓慢) for slice()。

此分類上一篇