How do I make the first letter of a string uppercase in JavaScript?

Created 22.06.2009 08:25
Viewed 2.42M times
4142 votes

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"
Underscore has a plugin called underscore.string that includes this and a bunch of other great tools. by Aaron, 15.04.2013 19:16
what about: return str.replace(/(\b\w)/gi,function(m){return m.toUpperCase();}); by Muhammad Umer, 21.11.2014 19:25
Simpler: string[0].toUpperCase() + string.substring(1) by dr.dimitru, 25.11.2015 04:00
`${s[0].toUpperCase()}${s.slice(1)}` by eaorak, 02.11.2019 20:20
([initial,]) => [initial.toUpperCase(),].join("") by Константин Ван, 06.01.2020 06:49
str.toLowerCase().replace(/\b(\w)/g, s => s.toUpperCase()) by Navruzbek Noraliev, 04.03.2020 11:17
Capitalize every word: str.replace(/(^\w|\s\w)/g, m => m.toUpperCase()) by chickens, 12.03.2020 13:14
For those using angular, there is a titlecase pipe: by Marche Remi, 27.01.2021 20:54
Show remaining 3 comments
Answers 50

The basic solution is:

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

console.log(capitalizeFirstLetter('foo')); // Foo

Some other answers modify String.prototype (this answer used to as well), but I would advise against this now due to maintainability (hard to find out where the function is being added to the prototype and could cause conflicts if other code uses the same name / a browser adds a native function with that same name in future).

...and then, there is so much more to this question when you consider internationalisation, as this astonishingly good answer (buried below) shows.

If you want to work with Unicode code points instead of code units (for example to handle Unicode characters outside of the Basic Multilingual Plane) you can leverage the fact that String#[@iterator] works with code points, and you can use toLocaleUpperCase to get locale-correct uppercasing:

const capitalizeFirstLetter = ([ first, ], locale = navigator.language) =>
  first.toLocaleUpperCase(locale) + rest.join('')

  capitalizeFirstLetter('foo'), // Foo
  capitalizeFirstLetter("𐐶𐐲𐑌𐐼𐐲𐑉"), // "𐐎𐐲𐑌𐐼𐐲𐑉" (correct!)
  capitalizeFirstLetter("italya", 'tr') // İtalya" (correct in Turkish Latin!)

For even more internationalization options, please see the original answer below.

22.06.2009 08:30

Here's a more object-oriented approach:

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

You'd call the function, like this:

"hello, world!".capitalize();

With the expected output being:

"Hello, World!"
20.07.2010 15:51
In your expected output, how in the world did the 'W' get capitalized? The whole string is 'hello, world!' and thus the first character is simply the 'h'. by Andy, 24.03.2021 07:55
(-1) as mentionned in the previous comment, your "expected output" would be "Hello, world!" with only the first letter as a capital letter. by Hicham O-Sfh, 04.05.2021 10:24


p:first-letter {
17.07.2012 14:06
$('#mystring_id').text(string).css('text-transform','capital‌​ize'); by DonMB, 24.09.2015 17:34
Additionally, this only affects the display of the string - not the actual value. If it's in a form, e.g., the value will still be submitted as-is. by dmansfield, 07.06.2016 13:26

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);


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);
28.08.2011 23:03

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

14.11.2015 03:26

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

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

// es6 using destructuring 
const capitalize = ([first,]) => first.toUpperCase() + rest.join('').toLowerCase();
19.07.2013 18:17

It seems to be easier in CSS:

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

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

09.12.2011 00:27
@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. by Adam Hepton, 18.01.2012 09:32
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. by Simon East, 21.01.2012 04:24
@Simon, the text-transform capitalizes first letter of every word and this is what Robert wants by DDK, 25.06.2012 08:42
Incorrect, Dinesh. He said the first character of the string. by Simon East, 26.06.2012 00:02
What's funny is that Ryan didn't help answer @Robert Willis's question. but he answered mine. by SoreThumb, 05.11.2012 01:59
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. by Dan Dascalescu, 07.11.2012 06:06
Agree with @DanDascalescu - Ryan's answer is completely wrong. by Timo Ernst, 14.11.2012 13:15
To capitalise the first letter you could use the first letter selector: p.capitalize :first-letter {text-transform: capitalize;} Apparently Safari struggles with this, but haven't looked into it. by Matt Parkins, 01.12.2012 11:34
The question specifies 'JavaScript'. A CSS solution doesn't provide this. by Holf, 22.03.2013 18:01
It's true that the question asks for JavaScript and only the first letter of the string, but the asker of the question isn't the only one here looking for an answer. It has obviously turned out to be a good answer for many people, resulting in upvotes. I certainly don't think it should be deleted. by Ali Gangji, 13.04.2013 08:54
It's now javascript: $('.capitalize').css('text-transform', 'capitalize') by Ali Gangji, 13.04.2013 08:58
The question specifies JavaScript. Anybody looking for a CSS based solution may not find this answer because they won't be searching for it. As it is, this is a useful bit of information that users might stumble across if they happen to be looking for a JavaScript solution. Regardless, this will capitalise all words, not the first letter of the string. Ryan has a good answer to a different question. He should delete this answer, create the right question, and then answer it there, if he wants to benefit the community. The points loss wouldn't be very conducive to doing this, I'll admit. :-) by Holf, 17.05.2013 16:56
So just wrap the tag around the single world you want capitalized by Nick Manning, 04.10.2013 05:40
This capitalizes every word's first letter. by MKN Web Solutions, 20.11.2013 20:35
I think, this answer is wrong, but when I searched answer to similar problem, I found this answer and it perfectly fits to my problem. So, thanks. by VikciaR, 13.12.2013 08:44
This answer is bad since it is not JavaScript. by ivkremer, 15.05.2014 21:44
@Jasny-ArnoldDaniels: You're correct, but this edit changes the meaning of the post too much. Better post it as a separate answer. Or rather downvote this and upvote that existing answer by Bergi, 18.05.2014 10:06
Show remaining 12 comments

I didn’t see any mention in the existing answers of issues related to astral plane code points or internationalization. “Uppercase” doesn’t mean the same thing in every language using a given script.

Initially I didn’t see any answers addressing issues related to astral plane code points. There is one, but it’s a bit buried (like this one will be, I guess!)

Most of the proposed functions look like this:

function capitalizeFirstLetter(str) {
  return str[0].toUpperCase() + str.slice(1);

However, some cased characters fall outside the BMP (basic multilingual plane, code points U+0 to U+FFFF). For example take this Deseret text:

capitalizeFirstLetter("𐐶𐐲𐑌𐐼𐐲𐑉"); // "𐐶𐐲𐑌𐐼𐐲𐑉"

The first character here fails to capitalize because the array-indexed properties of strings don’t access “characters” or code points*. They access UTF-16 code units. This is true also when slicing — the index values point at code units.

It happens to be that UTF-16 code units are 1:1 with USV code points within two ranges, U+0 to U+D7FF and U+E000 to U+FFFF inclusive. Most cased characters fall into those two ranges, but not all of them.

From ES2015 on, dealing with this became a bit easier. String.prototype[@@iterator] yields strings corresponding to code points**. So for example, we can do this:

function capitalizeFirstLetter([ first, ]) {
  return [ first.toUpperCase(), ].join('');

capitalizeFirstLetter("𐐶𐐲𐑌𐐼𐐲𐑉") // "𐐎𐐲𐑌𐐼𐐲𐑉"

For longer strings, this is probably not terribly efficient*** — we don’t really need to iterate the remainder. We could use String.prototype.codePointAt to get at that first (possible) letter, but we’d still need to determine where the slice should begin. One way to avoid iterating the remainder would be to test whether the first codepoint is outside the BMP; if it isn’t, the slice begins at 1, and if it is, the slice begins at 2.

function capitalizeFirstLetter(str) {
  const firstCP = str.codePointAt(0);
  const index = firstCP > 0xFFFF ? 2 : 1;

  return String.fromCodePoint(firstCP).toUpperCase() + str.slice(index);

capitalizeFirstLetter("𐐶𐐲𐑌𐐼𐐲𐑉") // "𐐎𐐲𐑌𐐼𐐲𐑉"

You could use bitwise math instead of > 0xFFFF there, but it’s probably easier to understand this way and either would achieve the same thing.

We can also make this work in ES5 and below by taking that logic a bit further if necessary. There are no intrinsic methods in ES5 for working with codepoints, so we have to manually test whether the first code unit is a surrogate****:

function capitalizeFirstLetter(str) {
  var firstCodeUnit = str[0];

  if (firstCodeUnit < '\uD800' || firstCodeUnit > '\uDFFF') {
    return str[0].toUpperCase() + str.slice(1);

  return str.slice(0, 2).toUpperCase() + str.slice(2);

capitalizeFirstLetter("𐐶𐐲𐑌𐐼𐐲𐑉") // "𐐎𐐲𐑌𐐼𐐲𐑉"

At the start I also mentioned internationalization considerations. Some of these are very difficult to account for because they require knowledge not only of what language is being used, but also may require specific knowledge of the words in the language. For example, the Irish digraph "mb" capitalizes as "mB" at the start of a word. Another example, the German eszett, never begins a word (afaik), but still helps illustrate the problem. The lowercase eszett (“ß”) capitalizes to “SS,” but “SS” could lowercase to either “ß” or “ss” — you require out-of-band knowledge of the German language to know which is correct!

The most famous example of these kinds of issues, probably, is Turkish. In Turkish Latin, the capital form of i is İ, while the lowercase form of I is ı — they’re two different letters. Fortunately we do have a way to account for this:

function capitalizeFirstLetter([ first, ], locale) {
  return [ first.toLocaleUpperCase(locale), ].join('');

capitalizeFirstLetter("italy", "en") // "Italy"
capitalizeFirstLetter("italya", "tr") // "İtalya"

In a browser, the user’s most-preferred language tag is indicated by navigator.language, a list in order of preference is found at navigator.languages, and a given DOM element’s language can be obtained (usually) with Object(element.closest('[lang]')).lang || YOUR_DEFAULT_HERE in multilanguage documents.

In agents which support Unicode property character classes in RegExp, which were introduced in ES2018, we can clean stuff up further by directly expressing what characters we’re interested in:

function capitalizeFirstLetter(str, locale=navigator.language) {
  return str.replace(/^\p{CWU}/u, char => char.toLocaleUpperCase(locale));

This could be tweaked a bit to also handle capitalizing multiple words in a string with fairly good accuracy. The CWU or Changes_When_Uppercased character property matches all code points which, well, change when uppercased. We can try this out with a titlecased digraph characters like the Dutch ij for example:

capitalizeFirstLetter('ijsselmeer'); // "IJsselmeer"

As of January 2021, all major engines have implemented the Unicode property character class feature, but depending on your target support range you may not be able to use it safely yet. The last browser to introduce support was Firefox (78; June 30, 2020). You can check for support of this feature with the Kangax compat table. Babel can be used to compile RegExp literals with property references to equivalent patterns without them, but be aware that the resulting code can sometimes be enormous. You probably would not want to do this unless you’re certain the tradeoff is justified for your use case.

In all likelihood, people asking this question will not be concerned with Deseret capitalization or internationalization. But it’s good to be aware of these issues because there’s a good chance you’ll encounter them eventually even if they aren’t concerns presently. They’re not “edge” cases, or rather, they’re not by-definition edge cases — there’s a whole country where most people speak Turkish, anyway, and conflating code units with codepoints is a fairly common source of bugs (especially with regard to emoji). Both strings and language are pretty complicated!

* The code units of UTF-16 / UCS2 are also Unicode code points in the sense that e.g. U+D800 is technically a code point, but that’s not what it “means” here ... sort of ... though it gets pretty fuzzy. What the surrogates definitely are not, though, is USVs (Unicode scalar values).

** Though if a surrogate code unit is “orphaned” — i.e., not part of a logical pair — you could still get surrogates here, too.

*** maybe. I haven’t tested it. Unless you have determined capitalization is a meaningful bottleneck, I probably wouldn’t sweat it — choose whatever you believe is most clear and readable.

**** such a function might wish to test both the first and second code units instead of just the first, since it’s possible that the first unit is an orphaned surrogate. For example the input "\uD800x" would capitalize the X as-is, which may or may not be expected.

26.12.2018 10:33
This answer needs to be moved to the front. by Rúnar Berg, 11.02.2020 18:57
Thanks @RúnarBerg — since your comment reminded me about this, I read over it again and realized I had left out a final case and solution worth mentioning. Also tried to clarify some of the terminology better. by Semicolon, 11.02.2020 22:48

This is the 2018 ECMAScript 6+ Solution:

const str = 'the Eiffel Tower';
const newStr = `${str[0].toUpperCase()}${str.slice(1)}`;
console.log('Original String:', str); // the Eiffel Tower
console.log('New String:', newStr); // The Eiffel Tower

19.03.2018 15:32

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

// => 'Fred'

// => 'FRED'

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

See their documentation:

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

// => 'fred'

// => 'fRED'

_.snakeCase('Foo Bar');
// => 'foo_bar'

Vanilla JavaScript for first upper case:

function upperCaseFirst(str){
    return str.charAt(0).toUpperCase() + str.substring(1);
29.11.2015 08:13
I think the preference should be for vanilla Js as most people will not download an entire framework only to capitalize a string. by GGG, 06.12.2015 23:49
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. by GGG, 08.12.2015 14:44

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(" ");
30.11.2011 17:16
Re-read question: I want to capitalize the first character of a string, but not change the case of any of the other letters. by JimmyPena, 30.11.2011 19:13
I know I did. I'd add one thing, in case the entire string starts capitalized: pieces[i] = j + pieces[i].substr(1).toLowerCase(); by Malovich, 20.12.2012 21:16
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. by Luke Channings, 10.03.2013 21:36
Would be better to first lowercase the whole string by Magico, 06.07.2016 10:36
Other than this function not answering the question, it's actually also overcomplicated. s => s.split(' ').map(x => x[0].toUpperCase() + x.slice(1)).join(' ') by OverCoder, 28.07.2017 18:10
String.prototype.capitalize = function(allWords) {
   return (allWords) ? // If all words
      this.split(' ').map(word => word.capitalize()).join(' ') : // Break down the phrase to words and then recursive
                                                                 // calls until capitalizing all words
      this.charAt(0).toUpperCase() + this.slice(1); // If allWords is undefined, capitalize only the first word,
                                                    // meaning the first character of the whole string

And then:

 "capitalize just the first word".capitalize(); ==> "Capitalize just the first word"
 "capitalize all words".capitalize(true); ==> "Capitalize All Words"

Update November 2016 (ES6), just for fun:

const capitalize = (string = '') => [...string].map(    // Convert to array with each item is a char of
                                                        // string by using spread operator (...)
    (char, index) => index ? char : char.toUpperCase()  // Index true means not equal 0, so (!index) is
                                                        // the first character which is capitalized by
                                                        // the `toUpperCase()` method
 ).join('')                                             // Return back to string

then capitalize("hello") // Hello

29.11.2013 20:01
I think this is a poor solution for 2 reasons: Modifying the prototype of a primitive is a bad idea. If the spec changes and they decide to pick 'capitalize' as a new proto property name, you're breaking core language functionality. Also, The method name chosen is poor. At first glance, I would think this will capitalize the entire string. Using a more descriptive name such as PHP's ucFirst or something similar might be a better idea. by dudewad, 22.02.2017 01:08
The other ES6 answer is simpler: const capitalize = ([first,]) => first.toUpperCase() + rest.join('').toLowerCase();. by Dan Dascalescu, 22.06.2019 05:50
@dudewad in css, capitalizing of first letter of a word is call 'capitalize', and if you want to capitalize all characters u use 'uppercase', hence it's not really bad choice. by Someone Special, 25.01.2021 10:56

CSS only

If the transformation is needed only for displaying on a web page:

p::first-letter {
  text-transform: uppercase;
  • Despite being called "::first-letter", it applies to the first character, i.e. in case of string %a, this selector would apply to % and as such a would not be capitalized.
  • In IE9+ or IE5.5+ it's supported in legacy notation with only one colon (:first-letter).

ES2015 one-liner

const capitalizeFirstChar = str => str.charAt(0).toUpperCase() + str.substring(1);


  • In the benchmark I performed, there was no significant difference between string.charAt(0) and string[0]. Note however, that string[0] would be undefined for an empty string, so the function would have to be rewritten to use "string && string[0]", which is way too verbose, compared to the alternative.
  • string.substring(1) is faster than string.slice(1).

Benchmark between substring() and slice()

The difference is rather minuscule nowadays (run the test yourself):

  • 21,580,613.15 ops/s ±1.6% for substring(),
  • 21,096,394.34 ops/s ±1.8% (2.24% slower) for slice().

Solutions' comparison

05.04.2017 17:21
You actually don't want to use the plus sign (+) as a concatenation method in ES6. You'll want to use template literals: by Sterling Bourne, 19.03.2018 15:37

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) ->

...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();
15.02.2013 06:55
There is a better way of doing this without modifying the String prototype. by Big McLargeHuge, 09.07.2013 20:42
@davidkennedy85 Sure! But this is the simple way, not the best way... ;-) by yckart, 09.07.2013 22:01
Dear lordy there's a million answers to this question! Your solution looks even nicer in es6. 'Answer'.replace(/^./, v => v.toLowerCase()) by stwilz, 29.07.2019 00:40
What are you referring to by "coffee"? "CoffeeScript"? by Peter Mortensen, 06.01.2021 23:38

SHORTEST 3 solutions, 1 and 2 handle cases when s string is "", null and undefined:

 s&&s[0].toUpperCase()+s.slice(1)        // 32 char

 s&&s.replace(/./,s[0].toUpperCase())    // 36 char - using regexp

'foo'.replace(/./,x=>x.toUpperCase())    // 31 char - direct on string, ES6

let s='foo bar';

console.log( s&&s[0].toUpperCase()+s.slice(1) );

console.log( s&&s.replace(/./,s[0].toUpperCase()) );

console.log( 'foo bar'.replace(/./,x=>x.toUpperCase()) );

19.09.2018 06:21

There is a very simple way to implement it by replace. For ECMAScript 6:

'foo'.replace(/^./, str => str.toUpperCase())


08.11.2018 08:31
Best answer by far, and extra points for showing the regex lambda syntax. I especially like this one as it can be a fluent cut-and-paste anywhere. by Wade Hatler, 11.01.2019 00:14
Using /^[a-z]/i will be better than using . as the prior one will not try to replace any character other than alphabets by Code Maniac, 06.07.2019 05:56
Very clever indeed! by codemonkey, 02.08.2020 04:19


var str = "ruby java";

console.log(str.charAt(0).toUpperCase() + str.substring(1));

It will output "Ruby java" to the console.

25.09.2014 16:13
One line solution. by Ahmad Sharif, 18.03.2020 15:33
String.prototype.capitalize = function(){
    return this.replace(/(^|\s)([a-z])/g, 
                        function(m, p1, p2) {
                            return p1 + p2.toUpperCase();


capitalizedString = someString.capitalize();

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

15.12.2010 10:15
Regular expressions are overkill for this. by Anthony Sottile, 14.06.2012 02:40
+1, this is what I was really looking for. There is a minor bug though, it ought to be return.this.toLocaleLowerCase().replace( ... by tomdemuyt, 14.01.2013 21:55
+1, I found this page looking for a javascript version of phps ucfirst, which I suspect is how most people find it. by Benubird, 09.04.2013 13:58
@DanDascalescu I found this useful, so +1 utilitarianism, and -1 anal-retentiveness. He included an example, so its function is clear. by Travis Webb, 02.08.2013 10:24
String.prototype.capitalize = function(){ return this.replace( /(^|\s)[a-z]/g , function(m){ return m.toUpperCase(); }); }; I refactor your code a bit, you need only a first match. by IGRACH, 28.04.2014 16:29
Firstly, it does something else than OP asked for, secondly regex is an inefficient overkill in this case, lastly don't modify prototypes of something you don't own by Przemek, 23.09.2017 19:32
Show remaining 1 comments

If you use Underscore.js or Lodash, the underscore.string library provides string extensions, including capitalize:

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


_.capitalize("foo bar") == "Foo bar"
12.06.2014 08:00
Since, version 3.0.0, Lo-Dash has this string method available by default. Just like described in this answer: _.capitalize("foo") === "Foo". by bardzusny, 09.04.2015 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'. by Stepan Zakharov, 07.05.2015 14:11
From version 4*, Lodash also lowercase() every other letter, be careful! by Igor Loskutov, 13.02.2016 08:33

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.

22.06.2009 08:33
Use String.substring() or String.slice() ... Don't use substr() - it's deprecated. by James, 22.06.2009 11:11
@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. by Dan Dascalescu, 07.11.2012 06: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". by Peter Rust, 21.11.2012 22:05
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. by Peter Rust, 21.11.2012 22:12
var capitalized = yourstring[0].toUpperCase() + yourstring.substr(1);
25.08.2016 12:29

It's always better to handle these kinds of stuff using CSS first, in general, if you can solve something using CSS, go for that first, then try JavaScript to solve your problems, so in this case try using :first-letter in CSS and apply text-transform:capitalize;

So try creating a class for that, so you can use it globally, for example: .first-letter-uppercase and add something like below in your CSS:

.first-letter-uppercase:first-letter {

Also the alternative option is JavaScript, so the best gonna be something like this:

function capitalizeTxt(txt) {
  return txt.charAt(0).toUpperCase() + txt.slice(1); //or if you want lowercase the rest txt.slice(1).toLowerCase();

and call it like:

capitalizeTxt('this is a test'); // return 'This is a test'
capitalizeTxt('the Eiffel Tower'); // return 'The Eiffel Tower'
capitalizeTxt('/index.html');  // return '/index.html'
capitalizeTxt('alireza');  // return 'Alireza'

If you want to reuse it over and over, it's better attach it to javascript native String, so something like below:

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

and call it as below:

'this is a test'.capitalizeTxt(); // return 'This is a test'
'the Eiffel Tower'.capitalizeTxt(); // return 'The Eiffel Tower'
'/index.html'.capitalizeTxt();  // return '/index.html'
'alireza'.capitalizeTxt();  // return 'Alireza'
14.05.2017 08:12

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
08.08.2011 16:55
Probably worth noting that this will also convert things like acronyms to lowercase, so maybe not the best idea in most cases by monokrome, 25.04.2016 05: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 by monokrome, 28.08.2016 03:25
btw, this will break uppercasing acronyms so be careful y'all <3 by monokrome, 15.03.2019 21:53
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'

=> '/index.html'
13.07.2015 20:34
Done @Ram. Also included examples. by Fredrik A., 23.07.2015 13:14
How is this any better than the 2009 answer?. by Dan Dascalescu, 27.01.2019 22:13
It isn't @DanDascalescu. I suppose you could argue that substr/substring is a bit more semantic as opposed to slice, but that's just a matter of preference. I did however include examples with the strings provided in the question, which is a nice touch not present in the '09 example. I honestly think it boils down to 15 year old me wanting karma on StackOverflow ;) by Fredrik A., 20.06.2019 11:50
var str = "test string";
str = str.substring(0,1).toUpperCase() + str.substring(1);
06.05.2014 05:15
yourString.replace(/\w/, c => c.toUpperCase())

I found this arrow function easiest. Replace matches the first letter character (\w) of your string and converts it to uppercase. Nothing fancier is necessary.

14.07.2018 19:40
This should be the accepted answer, instead it's almost the last since SO keeps awarding outdated questions. Btw, it's better using /./ for two reason: /\w/ will skip all the previous not letter characters (so @@abc will become @@Abc), and then it doesn't work with not-latin characters by Cristian Traìna, 29.04.2019 18:01
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.)

19.11.2012 18:33
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:… by Robin van Baalen, 13.02.2013 13:17
@RobinvanBaalen Your link is now broken. Got an updated one? by Brad, 23.01.2017 03:29
Regexp is overkill for this, prefer the simpler : str.charAt(0).toUpperCase() + str.slice(1) by Simon, 23.01.2017 13:36
@Brad unfortunately not by Robin van Baalen, 23.01.2017 18:54
Often times, if you want to solve your problem with regex, you end up with two problems. by Przemek, 23.09.2017 19:18

Check out this solution:

var stringVal = 'master';
stringVal.replace(/^./, stringVal[0].toUpperCase()); // Returns Master
23.08.2015 12:51
This should be the accepted answer. The main solution shouldn't use a framework like underscore. by Adam McArthur, 26.09.2015 07:58
Save some keystrokes ;) stringVal.replace(/^./, stringVal[0].toUpperCase()); by Alfredo Delgado, 15.10.2015 19:30
Regex shouldn't be used where not necessary. It's greatly inefficient and it doesn't make code any more concise either. Moreover, stringVal[0] would be undefined for empty stringVal, and as such attempt to access property .toUpperCase() would throw an error. by Przemek, 23.09.2017 19:28

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.

18.08.2010 21:07
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 by Hussam, 08.12.2011 14:29
One liner: string[0].toUpperCase() + string.substring(1) by dr.dimitru, 25.11.2015 04:01
@TarranJones here is bulletproof one liner: (string[0] || '').toUpperCase() + string.substring(1) by dr.dimitru, 06.05.2016 18:20
@dr.dimitru: Instead of idiomatic (string[0] || '') you could just string.charAt(0). by Przemek, 24.04.2017 18:24
What is "aclaration"? by Peter Mortensen, 06.01.2021 23:34

You can do it in one line like this

string[0].toUpperCase() + string.substring(1)
22.01.2018 18:27
This answer was already given in 2009. by Dan Dascalescu, 27.01.2019 22:11

In CoffeeScript, add to the prototype for a string:

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

Usage would be:


Which yields:

15.08.2012 18:06
This is a JavaScript question. by Cobby, 06.05.2014 00:54
@Cobby - And this is a coffeescript answer. by longda, 06.05.2014 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() } by Shiala, 16.07.2014 17:17
Coffeescript is a preprocessor language, not a library... A library for this would be silly by TaylorMac, 30.07.2014 20:18
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: by longda, 30.07.2014 23:28

Only because this is really a one-liner I will include this answer. It's an ES6-based interpolated string one-liner.

let setStringName = 'the Eiffel Tower';
setStringName = `${setStringName[0].toUpperCase()}${setStringName.substring(1)}`;
07.04.2020 06:10

Here's my version. I think it's easy to understand and elegant too.

var str = "foo bar baz";

// Capitalize
str.split(' ')
    .map(w => w[0].toUpperCase() + w.substr(1).toLowerCase())
    .join(' ')
// Returns "Foo Bar Baz"

// Capitalize the first letter
str.charAt(0).toUpperCase() + str.slice(1)
// Returns "Foo bar baz"
21.07.2014 06:02

There are already so many good answers, but you can also use a simple CSS transform:

text-transform: capitalize;

div.c {
  text-transform: capitalize;
<h2>text-transform: capitalize:</h2>
<div class="c">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>

28.09.2020 14:12
this will uppercase all words in a string by Barbu Barbu, 14.11.2020 16:57
no, it only capitalize ist letter of each word in a sentence‌​m by Deen John, 15.11.2020 01:36
i specifically mentioned that besides javascript you can use css too...not everyone is probably looking for an interview question answer. by Deen John, 07.01.2021 02:35

The first character of every string is capitalized.

function capitalize(word){
    return word[0].toUpperCase() + word.slice(1).toLowerCase();

console.log(capitalize("john")); //John
console.log(capitalize("BRAVO")); //Bravo
console.log(capitalize("BLAne")); //Blane

08.06.2020 10:12
first char of word to upper case = word[0].toUpperCase() skipe first char and lower rest = slice(1).toLowerCase(); by Omar bakhsh, 19.07.2020 01:10
This changes other characters too. The question asks "How do I make the first letter of a string uppercase, but not change the case of any of the other letters?" by Sean, 22.08.2020 20:28
you can ignore the other extra step of code : +word.slice(1).toLowerCase(); by Omar bakhsh, 23.08.2020 00:17


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

As a String prototype method:

String::capitalize = -> @charAt(0).toUpperCase() + @slice(1)
07.11.2011 20:39
Stupid question but how would you add this to the String prototype in coffeescript? by longda, 15.08.2012 17:54

A functional approach

const capitalize = ([s, ...tring]) =>
  [s.toUpperCase(), ...tring]

Then you could

const titleCase = str => 
    .split(' ')
    .join(' ')
10.08.2018 13:42
Don't forget toLowerCase() the remainder of the word. Passing a word in all caps to this current solution would keep it in all caps. by Aaron Tribou, 04.09.2018 11:19

𝗔 𝗦𝗼𝗹𝘂𝘁𝗶𝗼𝗻 𝗧𝗵𝗮𝘁 𝗪𝗼𝗿𝗸𝘀 𝗙𝗼𝗿 𝗔𝗹𝗹 𝗨𝗻𝗶𝗰𝗼𝗱𝗲 𝗖𝗵𝗮𝗿𝗮𝗰𝘁𝗲𝗿𝘀

5781 different answers for this question, some off-topic, and yet none of them raise the important issue that none of the solutions listed will work with Asian characters, emoji's, and other high Unicode-point-value characters in many browsers. Here is a solution that will:

const consistantCapitalizeFirstLetter = "\uD852\uDF62".length === 1 ?
    function(S) {
        "use-strict"; // Hooray! The browser uses UTF-32!
        return S.charAt(0).toUpperCase() + string.substring(1);
    } : function(S) {
        // The browser is using UCS16 to store UTF-16
        var code = S.charCodeAt(0)|0;
        return (
          code >= 0xD800 && code <= 0xDBFF ? // Detect surrogate pair
            S.slice(0,2).toUpperCase() + string.substring(2) :
            S.charAt(0).toUpperCase() + string.substring(1)
const prettyCapitalizeFirstLetter = "\uD852\uDF62".length === 1 ?
    function(S) {
        "use-strict"; // Hooray! The browser uses UTF-32!
        return S.charAt(0).toLocaleUpperCase() + string.substring(1);
    } : function(S) {
        // The browser is using UCS16 to store UTF-16
        var code = S.charCodeAt(0)|0;
        return (
          code >= 0xD800 && code <= 0xDBFF ? // Detect surrogate pair
            S.slice(0,2).toLocaleUpperCase() + string.substring(2) :
            S.charAt(0).toLocaleUpperCase() + string.substring(1)

Do note that the above solution tries to account for UTF-32. However, the specification officially states that browsers are required to do everything in UTF-16 mapped into UCS2. Nevertheless, if we all come together, do our part, and start preparing for UTF32, then there is a chance that the TC39 may allow browsers to start using UTF-32 (like how Python uses 24-bits for each character of the string). This must seem silly to an English speaker: no one who uses only latin-1 has ever had to deal with Mojibake because Latin-I is supported by all character encodings. But, users in other countries (such as China, Japan, Indonesia, etc.) are not so fortunate. They constantly struggle with encoding problems not just from the webpage, but also from the JavaScript: many Chinese/Japanese characters are treated as two letters by JavaScript and thus may be broken apart in the middle, resulting in � and � (two question-marks that make no sense to the end user). If we could start getting ready for UTF-32, then the TC39 might just allow browsers do what Python did many years ago which had made Python very popular for working with high Unicode characters: using UTF-32.

consistantCapitalizeFirstLetter works correctly in Internet Explorer 3+. prettyCapitalizeFirstLetter requires Internet Explorer 5.5+ (see the top of page 250 of this document). However, these fact are more of just jokes because it is very likely that the rest of the code on your webpage will not even work in Internet Explorer 8 - because of all the DOM and JScript bugs and lack of features in these older browsers. Further, no one uses Internet Explorer 3 or Internet Explorer 5.5 any more.

20.07.2017 20:49
Glad to see an answer that brings up this concern. However, I don’t believe there are any browsers where String.fromCodePoint(65536).length === 1 will be true. That ES strings expose their UTF16ishness isn’t implementation-specific behavior — it’s a well-defined part of the spec, and it can’t be fixed due to backwards compat. by Semicolon, 26.12.2018 10:48
@Semicolon Thank you for pointing out a flaw with my answer. I have appended an additional explanation accordingly. by Jack Giffin, 25.04.2019 16:30
Re: the new final notes, WHATWG and co have landed on UTF-8 as the sole ‘correct’ encoding for all text interchange on the platform. This isn’t gonna change (and it’s a good thing). The ES issue is distinct from that, though — it’s about ES having a string abstraction where the code units of the internal ‘utf-16 + lone surrogates’ encoding (it’s neither UTF-16 nor UCS2 quite) ‘break through’ when using indexed address, String.prototype.length, etc. (1/2) by Semicolon, 25.04.2019 20:54
The body responsible for ES is TC39 rather than W3C (or WHATWG, etc), and they cannot change the existing functionality because it would break the web. Instead, they can introduce new functionality that behaves correctly. They already have begun doing this — the 'u' flag on RegExp, String.prototype.codePointAt, and String.prototype[@@iterator] provide safer alternatives to the old APIs. (2/2) by Semicolon, 25.04.2019 20:55
@Semicolon Thank you for your correction. I have edited the content appropriately. by Jack Giffin, 25.04.2019 20:58
// Uppercase first letter
function ucfirst(field) {
    field.value = field.value.substr(0, 1).toUpperCase() + field.value.substr(1);


<input type="text" onKeyup="ucfirst(this)" />
02.08.2012 08:21
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. by abestic9, 17.05.2013 02:29

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);
08.05.2015 11:54
Man, this should be at the first page at very least by YakovL, 28.12.2017 16:42
I would go str = str.charAt(0).toLocaleUpperCase() + str.substr(1);, though, to make this shorter by YakovL, 28.12.2017 20:31
There is currently no answer by a user with the name "salim" (user names can change at any time). What answer does it refer to? by Peter Mortensen, 06.01.2021 23:23
function capitalize(string) {
    return string.replace(/^./,"".toUpperCase));
09.03.2015 18:22
this capitalizes the whole string by henhen, 25.06.2018 19:09
@henhen no, the regex character ^ asserts position at start. then . matches a single character by Martin Burch, 28.06.2018 16:51
 * As terse as possible, assuming you're using ES version 6+
var upLetter1=s=>s.replace(/./,m=>m.toUpperCase());

console.log(upLetter1("the quick brown fox jumped over the lazy dog."));
//\\ The quick brown fox jumped over the lazy dog. //\\
10.09.2019 23:37

This solution might be new and probably the simplest.

function firstUpperCase(input)
    return input[0].toUpperCase() + input.substr(1);

console.log(firstUpperCase("capitalize first letter"));

13.09.2017 21:50

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

14.11.2012 10:34

Using the JS replace string method & a regular expression w/ a word boundary seems simple.

Capitalize the first words' first character: "the eiffel tower" --> "The eiffel tower"

str.replace(/\b\w/, v => v.toUpperCase())

Capitalize all words' first character: "the eiffel tower" --> "The Eiffel Tower"

str.replace(/\b\w/g, v => v.toUpperCase())
20.01.2020 06:12

Using an arrow function:

const capitalize = string => string[0].toUpperCase() + string.slice(1)
18.11.2020 16:49

Unicode and Locale Aware

Using current language features:

function capitalize([firstLetter,]) {
  return [firstLetter.toLocaleUpperCase(),].join('');

console.log(capitalize('foo bar'));

// Title Case
  'Title Case:',
  'foo bar'
    .join(' '),

We accept a destructured string as the only parameter [firstLetter,], assigning the first character to the variable firstLetter and get an array for the rest of the characters ( bound to the rest variable. E.g. for the string lorem ipsum this should look like:

capitalize('lorem ipsum');
// firstLetter = 'l'
// rest = ['o', 'r', 'e', 'm', ' ', 'i', 'p', 's', 'u', 'm'];

Now all we need to do is prepend an uppercased version of the first letter firstLetter.toLocaleUpperCase() to the rest array—using the spread operator—and join the resulting array into a string using .join('')

30.10.2019 01:12
can you explain your function capitalize. by Amit Jamwal, 20.11.2019 10:34

Using prototypes

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

or Using functions

function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
09.03.2017 18:16


let a = 'hello',
    fix = a.slice(0,1).toUpperCase()+a.slice(1)

07.08.2018 16:54

There are multiple ways of doing this try some below

var lower = 'the Eiffel Tower';
var upper = lower.charAt(0).toUpperCase() + lower.substr(1);

And if you are comfortable with regular expressions, you do things this way:

var upper = lower.replace(/^\w/, function (chr) {
  return chr.toUpperCase();

And you can even take it one step further by using more modern syntax:

const upper = lower.replace(/^\w/, c => c.toUpperCase());

Also this will take care of negative scenarios as mentioned in example like words starting with special characters like !@#$%^&*()}{{[];':",.<>/? .

14.01.2019 15:38