如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
功能性方法
const capitalize = ([s, ...tring]) =>
[s.toUpperCase(), ...tring]
.join('');
然后你可以
const titleCase = str =>
str
.split(' ')
.map(capitalize)
.join(' ')
其他回答
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
一些其他答案修改 String.prototype(这个答案也被用来),但我会建议反对这一点现在由于可持续性(很难找到函数在哪里被添加到原型,如果另一个代码使用相同的名称 / 一个浏览器添加一个原始函数与相同的名称在未来可能导致冲突)。
咖啡文字
ucfirst = (str) -> str.charAt(0).toUpperCase() + str.slice(1)
作为一个严格的原型方法:
String::capitalize = -> @charAt(0).toUpperCase() + @slice(1)
使用原型
String.prototype.capitalize = function () {
return this.charAt(0) + this.slice(1).toLowerCase();
}
或使用功能
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1).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);
}
此分類上一篇
String.prototype.capitalize = function(allWords) {
return (allWords) ? // If all words
this.split(' ').map(word => word.capitalize()).join(' ') : // Break down the phrase to words and then recursive
// calls until capitalizing all words
this.charAt(0).toUpperCase() + this.slice(1); // If allWords is undefined, capitalize only the first word,
// meaning the first character of the whole string
}
然后:
"capitalize just the first word".capitalize(); ==> "Capitalize just the first word"
"capitalize all words".capitalize(true); ==> "Capitalize All Words"
更新2016年11月(ES6),只是为了乐趣:
const capitalize = (string = '') => [...string].map( // Convert to array with each item is a char of
// string by using spread operator (...)
(char, index) => index ? char : char.toUpperCase() // Index true means not equal 0, so (!index) is
// the first character which is capitalized by
// the `toUpperCase()` method
).join('') // Return back to string
此分類上一篇: 你好(Hello)