views:

9910

answers:

5

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
+8  A: 

Try this:

str.replace(/^\w/, function($0) { return $0.toUpperCase(); })
Gumbo
+56  A: 

Another solution:

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

Steve

Steve Harrison
+1 for readability. A simple problem like this doesn't need overkill.
karim79
Hm, I got an error here on the slice function. Changed to substr instead. Maybe it was something else that was wrong, but works here now at least :p
Svish
+2  A: 

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.

Robert Wills
Use String.substring() or String.slice() ... Don't use substr() - it's deprecated.
J-P
+14  A: 

A more object-oriented approach:

String.prototype.capitalize = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}

And then:

"hello world".capitalize();  =>  "Hello world"
Steve Hansell
+2 for readability *and* usability. Yum.
chadoh
A: 

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.

raphie