如何使字符串的第一个字母大写,但不更改任何其他字母的大小写?
例如:
"this is a test"
→"This is a test"
"the Eiffel Tower"
→"The Eiffel Tower"
"/index.html"
→"/index.html"
如何使字符串的第一个字母大写,但不更改任何其他字母的大小写?
例如:
"this is a test"
→ "This is a test"
"the Eiffel Tower"
→ "The Eiffel Tower"
"/index.html"
→ "/index.html"
基本的解决办法是:
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
console.log(capitalizeFirstLetter('foo')); // Foo
其他一些答案修改了String.prototype
(这个答案也曾经修改过),但由于可维护性,我现在建议不要这样做(很难找出函数被添加到的位置prototype
,如果其他代码使用相同的名称/浏览器,可能会导致冲突将来添加具有相同名称的本机函数)。
...然后,当您考虑国际化时,这个问题还有很多,正如这个惊人的好答案(埋在下面)所示。
如果您想使用 Unicode 代码点而不是代码单元(例如处理基本多语言平面之外的 Unicode 字符),您可以利用String#[@iterator]
使用代码点的事实,并且您可以使用toLocaleUpperCase
获得区域设置正确的大写:
const capitalizeFirstLetter = ([ first, ...rest ], locale = navigator.language) =>
first.toLocaleUpperCase(locale) + rest.join('')
console.log(
capitalizeFirstLetter('foo'), // Foo
capitalizeFirstLetter("𐐶𐐲𐑌𐐼𐐲𐑉"), // "𐐎𐐲𐑌𐐼𐐲𐑉" (correct!)
capitalizeFirstLetter("italya", 'tr') // İtalya" (correct in Turkish Latin!)
)
这是一种更面向对象的方法:
Object.defineProperty(String.prototype, 'capitalize', {
value: function() {
return this.charAt(0).toUpperCase() + this.slice(1);
},
enumerable: false
});
你会像这样调用这个函数:
"hello, world!".capitalize();
预期输出为:
"Hello, world!"
在 CSS 中:
p:first-letter {
text-transform:capitalize;
}
这是通过将字符串视为数组来获取第一个字母的流行答案的缩短版本:
function capitalize(s)
{
return s[0].toUpperCase() + s.slice(1);
}
根据下面的评论,这在 IE 7 或更低版本中不起作用。
为避免出现undefined
空字符串(参见下面@njzk2 的评论),您可以检查空字符串:
function capitalize(s)
{
return s && s[0].toUpperCase() + s.slice(1);
}
const capitalize = s => s && s[0].toUpperCase() + s.slice(1)
// to always return type string event when s may be falsy other than empty-string
const capitalize = s => (s && s[0].toUpperCase() + s.slice(1)) || ""
以下是基于此 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);
}