小编典典

如何在 JavaScript 中使字符串的第一个字母大写?

javascript

如何使字符串的第一个字母大写,但不更改任何其他字母的大小写?

例如:

  • "this is a test""This is a test"
  • "the Eiffel Tower""The Eiffel Tower"
  • "/index.html""/index.html"

阅读 246

收藏
2022-01-08

共2个答案

小编典典

基本的解决办法是:

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!)
)
2022-01-08
小编典典

这是一种更面向对象的方法:

Object.defineProperty(String.prototype, 'capitalize', {
  value: function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
  },
  enumerable: false
});

你会像这样调用这个函数:

"hello, world!".capitalize();

预期输出为:

"Hello, world!"
2022-01-08