I want to capitalize the first character of a string, and 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
I want to capitalize the first character of a string, and not change the case of any of the other letters. For example:
Try this:
str.replace(/^\w/, function($0) { return $0.toUpperCase(); })
Another solution:
function capitaliseFirstLetter(string)
{
return string.charAt(0).toUpperCase() + string.slice(1);
}
Steve
Here is a function called ucfirst() (short for "upper case first letter"):
function ucfirst(str) {
var firstLetter = str.substr(0, 1);
return firstLetter.toUpperCase() + str.substr(1);
}
You can capitalise a string by calling ucfirst("some string") -- for example,
ucfirst("this is a test") --> "This is a test"
It works by splitting the string into two pieces. On the first line it pulls out firstLetter and then on the second line it capitalises firstLetter by calling firstLetter.toUpperCase() and joins it with the rest of the string, which is found by calling str.substr(1).
You might think this would fail for an empty string, and indeed in a language like C you would have to cater for this. However in Javascript, when you take a substring of an empty string, you just get an empty string back.
A more object-oriented approach:
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
And then:
"hello world".capitalize(); => "Hello world"
The ucfirst function works if you do it like this
function ucfirst(str) {
var firstLetter = str.slice(0,1);
return firstLetter.toUpperCase() + str.substring(1);
}
Thanks J-P for the aclaration.