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"
"the Eiffel Tower"
-> "The Eiffel Tower"
"/index.html"
-> "/index.html"
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
其他一些答案修改了String.prototype
(这个答案同样适用),但由于可维护性(现在很难找到函数被添加到prototype
并且如果其他代码使用相同的方法可能会导致冲突),我会提出反对意见名称/浏览器将来会添加一个具有相同名称的本地函数)。
A more object-oriented approach:
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
And then:
"hello world".capitalize(); => "Hello world"
在CSS中:
p:first-letter {
text-transform:capitalize;
}
链接地址: http://www.djcxy.com/p/372.html
上一篇: 为什么字符[]优先于字符串的密码?