Join the Stack Overflow Community
Stack Overflow is a community of 6.3 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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
share|improve this question
5  
@tghw I think there are many answers here that are can be accepted. Some I would even consider excellent. But I'm wondering who will. It's not going to be Robert Wills since he hasn't been on SO for 3 years. For a discussion look here – Rembunator Mar 8 '13 at 10:00
9  
Underscore has a plugin called underscore.string that includes this and a bunch of other great tools. – Aaron Apr 15 '13 at 19:16
    
Salim beat me to what i think is the best answer. Crazy it took so long to get the one line of code – bobbdelsol May 8 '14 at 0:42
    
what about: return str.replace(/(\b\w)/gi,function(m){return m.toUpperCase();}); – Muhammad Umer Nov 21 '14 at 19:25
    
Simpler: string[0].toUpperCase() + string.substring(1) – dr.dimitru Nov 25 '15 at 4:00

53 Answers 53

up vote 3253 down vote
+50

Another solution:

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

You could also add it to the String.prototype so you could chain it with other methods:

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

and use it like this:

'string'.capitalizeFirstLetter() // String
share|improve this answer
7  
substring is understood in more browsers than substr – mplungjan Jul 6 '11 at 13:07
5  
to add to karim79 - its probably overkill to make it a function as javascript will do the same thing to the variable without the function wrapping. I suppose it would be more clear using a function, but its native otherwise, why complicate it with a function wrapper? – Ross Oct 24 '12 at 23:36
13  
Nevermind...""[0].toUpperCase() fails – Crisfole Jan 4 '13 at 19:42
5  
Shouldn't we also toLowerCase the slice(1) ? – hasen Jan 30 '14 at 17:58
53  
No, because the OP gave this example: the Eiffel Tower -> The Eiffel Tower. Plus, the function is called capitaliseFirstLetter not capitaliseFirstLetterAndLowerCaseAllTheOthers. – ban-geoengineering Aug 2 '14 at 10:24

A more object-oriented approach:

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

And then:

"hello world".capitalize();  =>  "Hello world" 
share|improve this answer
13  
I like this solution cause it's like Ruby, and Ruby is sweet! :) I lower case all the other letters of the string so that it works exactly like Ruby: return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase(); – mattdipasquale Mar 8 '11 at 18:21
3  
The slice needs to be lowercase. – Keyo Jun 19 '11 at 21:17
97  
In this post-Prototype.js world, it is not suggested to change or extend the native objects. – rxgx Jul 25 '11 at 22:24
124  
@rxgx - The "don't extend" boogeyman is now starting to die off (thank god), and people are pulling their heads out of the jSand and realizing it is just a language feature. Just because Prototype.js extended Object itself for a brief time, doesn't mean extending Natives is bad. You shouldn't do it if you're writing code for an unknown consumer (like an analytics script that goes on random sites), but other than that it's fine. – csuwldcat May 19 '12 at 20:47
10  
@csuwldcat What if another library that you are using adds its own capitalize without you knowing it? Extending prototypes is bad form regardless if Prototype.js did it or not. With ES6, intrinsics will allow you to have your cake and eat it too. I think you might confusing the "boogeyman" dying off for people creating shims that comply with the ECMASCRIPT spec. These shims are perfectly fine because another library that added a shim would implement it in the same way. However, adding your own non-spec intrinsics should be avoided. – Justin Meyer Sep 17 '14 at 20:37

In CSS:

p:first-letter {
    text-transform:capitalize;
}
share|improve this answer
15  
+1 for the only CSS solution that capitalizes only the first letter of the string, as the asker asked, not the whole string. Might as well use text-transform: uppercase in that case. – Dan Dascalescu Nov 7 '12 at 6:13
    
Reports of issues for this solution in Safari - some people getting an additional letter in some versions. – Matt Parkins Dec 1 '12 at 11:35
16  
OP is asking for a JS solution. – Antonio Max Sep 23 '13 at 15:23
9  
$('#mystring_id').text(string).css('text-transform','capital‌​ize'); – DonMB Sep 24 '15 at 17:34
1  
+1 - I found the reminder than I can do this in CSS very helpful, as I am only capitalizing for display (text copying is not a concern). – Iiridayn Apr 6 at 22:29

Here is a shortened version of the popular answer that gets the first letter by treating the string as an array:

function capitalize(s)
{
    return s[0].toUpperCase() + s.slice(1);
}

Update:

According to the comments below this doesn't work in IE 7 or below.

Update 2:

To avoid undefined for empty strings (see @njzk2's comment below), you can check for an empty string:

function capitalize(s)
{
    return s && s[0].toUpperCase() + s.slice(1);
}
share|improve this answer
19  
This won’t work in IE < 8, as those browsers don’t support string indexing. IE8 itself supports it, but only for string literals — not for string objects. – Mathias Bynens Feb 14 '12 at 11:33
19  
Figures IE would cry... – joelvh Jul 13 '12 at 7:47
32  
who cares, IE7 market is less than 5%! and those are probably your gremma's and grempa's old machine. I say short code FTW! – vsync Dec 3 '12 at 6:20
24  
@vsync your gremma and grempa may have a lot of money they are willing to spend on my site... – joshuahedlund Mar 12 '14 at 14:40
2  
@vsync I just meant that depending on your user demographics, sometimes (though gratefully less and less as we pass 2014 and beyond) it is profitable to support old browsers like IE7... – joshuahedlund Mar 14 '14 at 17:47

If you're interested in the performance of a few different methods posted:

Here are the fastest methods based on this jsperf test (ordered from fastest to slowest).

As you can see, the first two methods are essentially comparable in terms of performance, whereas altering the String.prototype is by far the slowest in terms of performance.

// 10,889,187 operations/sec
function capitalizeFirstLetter(string) {
    return string[0].toUpperCase() + string.slice(1);
}

// 10,875,535 operations/sec
function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}

// 4,632,536 operations/sec
function capitalizeFirstLetter(string) {
    return string.replace(/^./, string[0].toUpperCase());
}

// 1,977,828 operations/sec
String.prototype.capitalizeFirstLetter = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}

enter image description here

share|improve this answer
    
It seems the initialization code doesn't make the difference either: jsperf.com/capitalize-first-letter-of-string/2 – user420667 Mar 22 at 17:59
1  
One more reason not to extend the prototype. – cchamberlain Jun 21 at 18:47

For another case I need it to capitalize the first letter and lowercase the rest. The following cases made me change this function:

//es5
function capitalize(string) {
    return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
capitalise("alfredo")  // => "Alfredo"
capitalise("Alejandro")// => "Alejandro
capitalise("ALBERTO")  // => "Alberto"
capitalise("ArMaNdO")  // => "Armando"

// es6 using destructuring 
const capitalize = ([first,...rest]) => first.toUpperCase() + rest.join('').toLowerCase();
share|improve this answer
    
"...but not change the case of any of the other letters". This is not a correct answer to the question the OP asked. – Carlos Muñoz Jul 1 '14 at 19:31
1  
@CarlosMuñoz if you read the opening sentence he says this is for a different case. – Tom Hart Sep 5 '14 at 8:25
    
@TomHart That's exactly why it's not a solution for the question. It should be a comment or another question and answer – Carlos Muñoz Sep 5 '14 at 13:38
5  
I do agree with you on that, but I can see a lot of people ending up here looking to do what this answer does. – Tom Hart Sep 5 '14 at 13:43

Capitalize the first letter of all words in a string:

function ucFirstAllWords( str )
{
    var pieces = str.split(" ");
    for ( var i = 0; i < pieces.length; i++ )
    {
        var j = pieces[i].charAt(0).toUpperCase();
        pieces[i] = j + pieces[i].substr(1);
    }
    return pieces.join(" ");
}
share|improve this answer
11  
Re-read question: I want to capitalize the first character of a string, but not change the case of any of the other letters. – JimmyPena Nov 30 '11 at 19:13
1  
I know I did. I'd add one thing, in case the entire string starts capitalized: pieces[i] = j + pieces[i].substr(1).toLowerCase(); – Malovich Dec 20 '12 at 21:16
2  
Another solution to this case: function capitaliseFirstLetters(s) { return s.split(" ").map(function(w) { return w.charAt(0).toUpperCase() + w.substr(1) }).join(" ") } Can be a nice one-liner if it's not put into a function. – Luke Channings Mar 10 '13 at 21:36
    
Would be better to first lowercase the whole string – Magico Jul 6 at 10:36
var string = "hello world";
string = string.charAt(0).toUpperCase() + string.slice(1);
alert(string);
share|improve this answer

We could get the first character with one of my favorite RegExp, looks like a cute smiley: /^./

String.prototype.capitalize = function () {
  return this.replace(/^./, function (match) {
    return match.toUpperCase();
  });
};

And for all coffee-junkies:

String::capitalize = ->
  @replace /^./, (match) ->
    match.toUpperCase()

...and for all guys who think that there's a better way of doing this, without extending native prototypes:

var capitalize = function (input) {
  return input.replace(/^./, function (match) {
    return match.toUpperCase();
  });
};
share|improve this answer
    
There is a better way of doing this without modifying the String prototype. – Dave Kennedy Jul 9 '13 at 20:42
2  
@davidkennedy85 Sure! But this is the simple way, not the best way... ;-) – yckart Jul 9 '13 at 22:01

If you use underscore.js or Lo-Dash, the underscore.string library provides string extensions, including capitalize:

_.capitalize(string) Converts first letter of the string to uppercase.

Example:

_.capitalize("foo bar") == "Foo bar"
share|improve this answer
2  
Since, version 3.0.0, Lo-Dash has this string method available by default. Just like described in this answer: _.capitalize("foo") === "Foo". – bardzusny Apr 9 '15 at 19:09
    
Also there are usefull underscore.js function called humanize. It converts an underscored, camelized, or dasherized string into a humanized one. Also removes beginning and ending whitespace, and removes the postfix '_id'. – jamesdevar May 7 '15 at 14:11
    
From version 4*, Lodash also lowercase() every other letter, be careful! – Igor Loskutov Feb 13 at 8:33

It seems to be easier in CSS:

<style type="text/css">
    p.capitalize {text-transform:capitalize;}
</style>
<p class="capitalize">This is some text.</p>

This is from CSS text-transform Property (at W3Schools).

share|improve this answer
25  
@Simon It's not stated that the string is necessarily going to be output as part of a HTML document - CSS is only going to be of use if it is. – Adam Hepton Jan 18 '12 at 9:32
7  
Adam, true, but I'd guess that over 95% of the Javascript out there is used with HTML & CSS. Unfortunately, the "capitalize" statement actually capitalizes every word, so you'd still need JS to capitalize only the first letter of the string. – Simon East Jan 21 '12 at 4:24
14  
Incorrect, Dinesh. He said the first character of the string. – Simon East Jun 26 '12 at 0:02
71  
This answer, despite having a ridiculous number of upvotes, is just wrong, as it will capitalize the first letter of every word. @Ryan, you'll earn a Disciplined badge if you delete it. Please do so. – Dan Dascalescu Nov 7 '12 at 6:06
8  
Agree with @DanDascalescu - Ryan's answer is completely wrong. – Timo Nov 14 '12 at 13:15
function capitalize(s) {
    // returns the first letter capitalized + the string from index 1 and out aka. the rest of the string
    return s[0].toUpperCase() + s.substr(1);
}


// examples
capitalize('this is a test');
=> 'This is a test'

capitalize('the Eiffel Tower');
=> 'The Eiffel Tower'

capitalize('/index.html');
=> '/index.html'
share|improve this answer
1  
Please explain the code and how it works – Ram Jul 14 '15 at 14:47
    
Done @Ram. Also included examples. – Fredrik A. Jul 23 '15 at 13:14

If you are wanting to reformat all-caps text, you might want to modify the other examples as such:

function capitalize (text) {
    return text.charAt(0).toUpperCase() + text.slice(1).toLowerCase();
}

This will ensure that the following text is changed:

TEST => Test
This Is A TeST => This is a test
share|improve this answer
    
Probably worth noting that this will also convert things like acronyms to lowercase, so maybe not the best idea in most cases – monokrome Apr 25 at 5:08
    
Also,did GAMITG really make an edit just to remove a piece of whitespace from a non-code portion of the post? O_O – monokrome Aug 28 at 3:25
String.prototype.capitalize=function(all){
    if(all){
       return this.split(' ').map(e=>e.capitalize()).join(' ');
    }else{
         return this.charAt(0).toUpperCase() + this.slice(1);
    }
}

And then:

 "capitalize just the first word".capitalize(); ==> "Capitalize just the first word"
  "capitalize all words".capitalize(true); ==> "Capitalize All Words"
share|improve this answer
String.prototype.capitalize = function(){
    return this.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase();
    } );
};

Usage:

capitalizedString = someString.capitalize();

This is a text string => This Is A Text String

share|improve this answer
12  
Regular expressions are overkill for this. – Anthony Sottile Jun 14 '12 at 2:40
3  
This answer is just wrong, as it will capitalize the first letter of every word, while the asker specifically asked for capitalizing only the first letter. @Murat, you'll earn a Disciplined badge if you delete it. Please do so. – Dan Dascalescu Nov 7 '12 at 6:10
    
+1, this is what I was really looking for. There is a minor bug though, it ought to be return.this.toLocaleLowerCase().replace( ... – tomdemuyt Jan 14 '13 at 21:55
    
+1, I found this page looking for a javascript version of phps ucfirst, which I suspect is how most people find it. – Benubird Apr 9 '13 at 13:58
    
@DanDascalescu I found this useful, so +1 utilitarianism, and -1 anal-retentiveness. He included an example, so its function is clear. – Travis Webb Aug 2 '13 at 10:24
var str = "test string";
str = str.substring(0,1).toUpperCase() + str.substring(1);
share|improve this answer

Checkout this solution:

var stringVal = 'master';
stringVal.replace(/^./, stringVal[0].toUpperCase()); // returns Master 
share|improve this answer
3  
This should be the accepted answer. The main solution shouldn't use a framework like underscore. – Adam McArthur Sep 26 '15 at 7:58
2  
Save some keystrokes ;) stringVal.replace(/^./, stringVal[0].toUpperCase()); – Alfredo Delgado Oct 15 '15 at 19:30
    
Yes, that also works. – Raju Bera Oct 26 '15 at 20:54
yourString.replace(/^[a-z]/, function(m){ return m.toUpperCase() });

(You may encapsulate it in a function or even add it to the String prototype if you use it frequently.)

share|improve this answer
3  
Even though this has quite some votes, this is by far the slowest solution posted here. I've put together a little speedtest with the most popular answers from this post, here: forwebonly.com/… – Robin van Baalen Feb 13 '13 at 13:17

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.

share|improve this answer
4  
Use String.substring() or String.slice() ... Don't use substr() - it's deprecated. – James Jun 22 '09 at 11:11
6  
@999: where does it say that substr() is deprecated? It's not, even now, three years later, let alone back in 2009 when you made this comment. – Dan Dascalescu Nov 7 '12 at 6:12
    
substr() may not be marked as deprecated by any popular ECMAScript implementation (I doubt it's not going to disappear anytime soon), but it's not part of the ECMAScript spec. The 3rd edition of the spec mentions it in the non-normative annex in order to "suggests uniform semantics for such properties without making the properties or their semantics part of this standard". – Peter Rust Nov 21 '12 at 22:05
1  
Having 3 methods that do the same thing (substring, substr and slice) is too many, IMO. I always use slice because it supports negative indexes, it doesn't have the confusing arg-swapping behavior and its API is similar to slice in other languages. – Peter Rust Nov 21 '12 at 22:12
var capitalized = yourstring[0].toUpperCase() + yourstring.substr(1);
share|improve this answer
1  
The simplest working solution, thanks dude. – Wessam El Mahdy Sep 23 at 22:15

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.

share|improve this answer
2  
nice name for the function! It's name is identical to the PHP equivalent. There is actually an entire library of PHP functions written in JS; it's called PHP.js and to be found on http://phpjs.org – Hussam Dec 8 '11 at 14:29
9  
One liner: string[0].toUpperCase() + string.substring(1) – dr.dimitru Nov 25 '15 at 4:01
    
@Hussam the URL changed to: locutusjs.io – pixel 67 May 5 at 10:08
    
@dr.dimitru wont work with empty string – TarranJones May 6 at 16:25
    
@TarranJones here is bulletproof one liner: (string[0] || '').toUpperCase() + string.substring(1) – dr.dimitru May 6 at 18:20

In CoffeeScript, add to the prototype for a string:

String::capitalize = ->
  @substr(0, 1).toUpperCase() + @substr(1)

Usage would be:

"woobie".capitalize()

Which yields:

"Woobie"
share|improve this answer
7  
This is a JavaScript question. – Cobby May 6 '14 at 0:54
12  
@Cobby - And this is a coffeescript answer. – longda May 6 '14 at 19:29
    
I think what Cobby is trying to say that some idiots are trying to accomplish every simple JavaScript task using stupid libraries while the very same solution in vanilla is as simple as String.prototype.capitalize = function () { return this.substring(0,1).toUpperCase() + this.substring(1).toLowerrCase() } – Shiala Jul 16 '14 at 17:17
1  
Coffeescript is a preprocessor language, not a library... A library for this would be silly – TaylorMac Jul 30 '14 at 20:18
3  
Let the record state: CoffeeScript is a little language that compiles into JavaScript. Furthermore, The golden rule of CoffeeScript is: "It's just JavaScript." I think if someone truly understands those two sentences, you'll understand why I included this answer. Hopefully that cleared things up for everyone. Source: coffeescript.org – longda Jul 30 '14 at 23:28

If you're already (or considering) using lodash, the solution is easy:

_.upperFirst('fred');
// => 'Fred'

_.upperFirst('FRED');
// => 'FRED'

_.capitalize('fred') //=> 'Fred'

See their docs: https://lodash.com/docs#capitalize

_.camelCase('Foo Bar'); //=> 'fooBar'

https://lodash.com/docs/4.15.0#camelCase

_.lowerFirst('Fred');
// => 'fred'

_.lowerFirst('FRED');
// => 'fRED'

_.snakeCase('Foo Bar');
// => 'foo_bar'
share|improve this answer
2  
I think the preference should be for vanilla Js as most people will not download an entire framework only to capitalize a string. – GGG Dec 6 '15 at 23:49
    
sure, but most people probably have lodash already loaded. – chovy Dec 7 '15 at 7:20
2  
In all my projects so far I've never used lodash. Don't forget either that most people on google will end on this page, and listing a framework as an alternative is fine, but not as a main answer. – GGG Dec 8 '15 at 14:44
    
This is wrong answer as Lodash#capitalize will downcase all other letters as well, i.e. capitalize('fooBar') will return Foobar instead of FooBar. Lodash has upperFirst for this. – medik Sep 15 at 22:56
    
@medik i updated the answer – chovy Sep 16 at 21:24
// Uppercase first letter
function ucfirst(field) {
    field.value = field.value.substr(0, 1).toUpperCase() + field.value.substr(1);
}

Usage:

<input type="text" onKeyup="ucfirst(this)" />
share|improve this answer
    
There was no reference to an input field or the requirement of an event to handle this. Aside from that, field.value could be shortened with a variable for readability. – Andrew Bestic May 17 '13 at 2:29

CoffeeScript

ucfirst = (str) -> str.charAt(0).toUpperCase() + str.slice(1)

As String prototype method:

String::capitalize = -> @charAt(0).toUpperCase() + @slice(1)
share|improve this answer
    
Stupid question but how would you add this to the String prototype in coffeescript? – longda Aug 15 '12 at 17:54

If you go with one of the regex answers, remember they will only work with ASCII characters. All your unicode letters will not be uppercased. The XRegExp library and its unicode plugins solve this problem if you want to stick with regexps. So something like this would work:

String.prototype.capitalize = function () {
    return this.replace(XRegExp("^\\p{L}"), function ($0) { return $0.toUpperCase(); })
}

Considering that it still doesn't cover all possibilities (combined characters, see http://www.regular-expressions.info/unicode.html) it seems easier to just use the .charAt(0).toUpperCase() approach.

share|improve this answer
var str = "ruby java";

alert(str.charAt(0).toUpperCase() + str.substring(1));

it will return "Ruby java"

http://jsfiddle.net/amitpandya/908c8e2v/

result link in jsfiddle

share|improve this answer
    
As it is now it won't return anything. – Sébastien Sep 25 '14 at 17:13
    
@Sébastien I attached jsfiddle source and result link – AMIC MING Sep 25 '14 at 17:21

Posting an edit of @salim's answer to include locale letter transformation.

var str = "test string";
str = str.substring(0,1).toLocaleUpperCase() + str.substring(1);
share|improve this answer

One possible solution:

function ConvertFirstCharacterToUpperCase(text) {
    return text.substr(0, 1).toUpperCase() + text.substr(1);    
}

Use this:

 alert(ConvertFirstCharacterToUpperCase("this is string"));

Here is working JS Fiddle

share|improve this answer

Or you could use Sugar.js capitalize()

Example:

'hello'.capitalize()           -> 'Hello'
'hello kitty'.capitalize()     -> 'Hello kitty'
'hello kitty'.capitalize(true) -> 'Hello Kitty'
share|improve this answer

protected by Engineer Jul 18 '13 at 5:43

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.