Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
398 views
in Technique[技术] by (71.8m points)

javascript - 如何在JavaScript中将字符串的首字母大写?(How do I make the first letter of a string uppercase in JavaScript?)

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

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

For example:

(例如:)

  • "this is a test" -> "This is a test"

    ("this is a test" -> "This is a test")

  • "the Eiffel Tower" -> "The Eiffel Tower"

    ("the Eiffel Tower" -> "The Eiffel Tower")

  • "/index.html" -> "/index.html"

    ("/index.html" -> "/index.html")

  ask by Robert Wills translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}

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).

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...