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

查看:155
本文介绍了如何在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"

推荐答案

function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}

其他一些答案修改 String.prototype (这个答案也是如此),但由于可维护性,我现在建议不要这样做(很难找到函数添加到原型的位置如果其他代码使用相同的名称/浏览器将来添加具有相同名称的本机函数,则可能导致冲突。

Some other answers modify String.prototype (this answer used to as well), but I would advise against this now due to maintainability (hard to find out where the function is being added to the prototype and could cause conflicts if other code uses the same name / a browser adds a native function with that same name in future).

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

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