如何在JavaScript中制作字符串大写的第一个字母?
如何使字符串的第一个字母大写,但不改变任何其他字母的大小写?
例如:
"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
并且如果其他代码使用相同的方法可能会导致冲突),我会提出反对意见名称/浏览器将来会添加一个具有相同名称的本地函数)。
更面向对象的方法:
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
接着:
"hello world".capitalize(); => "Hello world"
在CSS中:
p:first-letter {
text-transform:capitalize;
}
链接地址: http://www.djcxy.com/p/371.html
上一篇: How do I make the first letter of a string uppercase in JavaScript?