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

例如:

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


当前回答

当我们说资本时,这意味着每个字中的第一个字母应该在上方,而成功的字符则在下方。

第一個函數下有兩個函數,第一個函數將使一條字符的第一個字符在上方,成功的字符在下方,第二個函數將使一條字符在標題字符,這意味著每個字符的第一個字符將在頭部。

// Will make will first letter of a sentence or word uppercase function capital(word){ word = word.toLowerCase() return word[0].toUpperCase() + word.substring(1); } // Will make first letter in each word capital function titleCase(title) { title = title.toLowerCase(); const words = title.split(' '); const titleCaseWords = words.map(word) => word[0].toUpperCase() + word.substring(

其他回答

好吧,这里是一个更简单的方法,空间线和这一切。

首先,你應該知道,一條線是一系列字符。

这个答案应该在所有空间线上工作。

假设你的字符串在一个变量 yourString:

const yourString = "el salvacion sucks" const capitalizeString = yourString.split(" ").长度 > 0? yourString.split(" ").map((item) => 项目[0].toUpperCase() + 项目.substring(1)).join(" ") : yourString[0].toUpperCase() + yourString.substring(1) console.log(capitalizeString)

点击 Run Code Snippet 按钮查看结果

使用原型

String.prototype.capitalize = function () {
    return this.charAt(0) + this.slice(1).toLowerCase();
  }

或使用功能

function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
}

在 CoffeeScript 中,添加一个字符串的原型:

String::capitalize = ->
  @substr(0, 1).toUpperCase() + @substr(1)

使用将是:

"woobie".capitalize()

谁得益:

"Woobie"

只有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()。

此分類上一篇

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

使用:

capitalizedString = someString.capitalize();

此分類上一篇: This Is a Text String