如何在 JavaScript 中使字符串的第一个字母大写? [英] How do I make the first letter of a string uppercase in JavaScript?

查看:22
本文介绍了如何在 JavaScript 中使字符串的第一个字母大写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I make the first letter of a string uppercase, but not change the case of any of the other letters?

例如:

  • 这是一个测试"这是一个测试"
  • 《埃菲尔铁塔》《埃菲尔铁塔》
  • /index.html"/index.html"
  • "this is a test""This is a test"
  • "the Eiffel Tower""The Eiffel Tower"
  • "/index.html""/index.html"

推荐答案

这里有一个更面向对象的方法:

Here's a more object-oriented approach:

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

你会像这样调用函数:

"hello, world!".capitalize();

预期输出为:

"Hello, world!"

这篇关于如何在 JavaScript 中使字符串的第一个字母大写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆