By Robert Wills


2009-06-22 08:25:31 8 Comments

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"

30 comments

@Steve Hansell 2010-07-20 15:51:07

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" 

@ma11hew28 2011-03-08 18:21:04

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

@Ryan 2011-07-25 22:24:09

In this post-Prototype.js world, it is not suggested to change or extend the native objects.

@codecowboy 2011-08-22 14:07:05

@rxgx can you point me to an article which explains your comment?

@csuwldcat 2012-05-19 20:47:18

@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.

@Robin van Baalen 2013-02-13 13:18:44

"string".charAt(0) is actually a little slower than "string"[0]. Edit: @MathiasBynens noted that my solution doesn't work consistently in IE. Therefore I suppose .charAt(0) is the best way to go.

@user656925 2013-04-12 16:19:55

...charAt() is bit faster ... stackoverflow.com/questions/15913406/…

@etoxin 2013-08-21 02:41:29

Had a fringe case where I had to use this on an uppercase string. I modified it a little. return this.charAt(0).toUpperCase() + this.slice(1).toLowerCase();

@YingYang 2014-03-04 09:53:56

Since rxgx's link is broken: perfectionkills.com/extending-native-builtins

@Hermann Ingjaldsson 2014-04-01 11:29:57

readability would be improved by naming the function 'capitalize_first_letter', because that's what it does. bug good answer though.

@Caley Woods 2014-06-05 18:31:36

According to jsPerf substr() is more performant than slice(). Source: jsperf.com/slice-vs-substr-vs-substring-methods-long-string/‌​2

@Justin Meyer 2014-09-17 20:37:27

@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.

@phreakhead 2014-12-30 01:03:04

Extending natives is EXTREMELY bad practice. Even if you say "oh I'm never going to use this code with anything else", you (or someone else) probably will. Then they will spend three days trying to figure out some weird math bug because someone extended Number.money() to deal with currency slightly different than your other library did. Seriously, I've seen this happen at a big company and it's not worth anyone's time debugging to figure out a library dev messed with the natives prototypes.

@Nick Sotiros 2015-03-12 06:56:35

make it a get property and you can do 'this sentence'.capitalized

@dperjar 2015-03-31 16:04:53

The toLocaleUpperCase() method returns the calling string value converted to upper case, according to any locale-specific case mappings. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

@David Mihal 2015-04-08 00:30:38

Extending natives appears to be substantially slower jsperf.com/string-prototype-or-function

@DanteTheSmith 2017-05-24 13:44:03

BIG reason to avoid extending prototype is speed. Whenever there is alternative solution that is even remotely as practical as it, use that. Personaly I always think 3 times before I use prototype and usually opt for it only when I wanna write a debug helpers or stuff like that, that will never go to production. The second example is when I need the said functionality everywhere and it makes it easier to remember when is bound to the class. Let's say I need a function with strings, that I am gonna use A LOT. Makes sense to prototype it in String.

@DanteTheSmith 2017-05-24 13:46:06

It depends tho, if you gonna repeat that on a dataset of a couple of million users, definitely don't go the prototype way.

@Webwoman 2019-02-06 16:23:33

Is it possible to return directly this like return this = this.charAt(0).toUpperCase() + this.slice(1) ?

@johncip 2019-02-25 05:11:51

Context matters; no reason to cargo cult this. "What if another library ... adds its own capitalize without you knowing it?" Since capitalization is well-defined, they won't differ unless one is wrong. -- "BIG reason to avoid extending prototype is speed." In the general case, maybe, but here? I know you mean "this is something to consider" and not "micro-optimize and skip the profiler." But if you need to capitalize millions of items, use the db. (And if you can't, you likely have problems that swapping methods for functions won't solve.)

@johncip 2019-02-25 05:19:51

That said, I suppose that some teams will be hoping that applying a consistent style will keep people from doing dumb things. It's an easy thing to lint for and be sure it won't bite you. I'll just say that it's not a substitute for real code reviews, and it's important not to turn good practice into superstition.

@Kamil Ibadov 2017-02-16 05:30:10

Here are the best solutions:

First Solution In CSS:

p {
  text-transform: capitalize;
}

Second solution :

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

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).toLowerCase();
}

and use it like this:

'string'.capitalizeFirstLetter() // String

Third Solution:

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).toLowerCase();
    }
    return pieces.join(" ");
}

@Gcap 2017-03-20 17:46:46

I found string.replace(string[0], string[0].toUpperCase()); to be a lot easier

@Andris 2017-07-25 10:13:16

Just a heads up - with the CSS solution the capitalised character cannot be visually selected in Chrome on Ubuntu (probably other browsers too) while selecting the text. It still gets selected and text is copied if you press Ctrl+C though.

@Ward D.S. 2017-09-01 07:52:49

The second solution, as you wrote it, makes the rest of the string lower case. Removing that would be closer to the original request. ("the Eiffel Tower" keeps the capitalization on the E and T)

@Przemek 2017-10-11 16:50:54

1) Use two colon notation of ::first-letter as this variant is in line with CSS3 philosophy when it comes to those colons, 2) use .substring(…) rather than .slice(…) as it has better performance, 3) OP didn't wanted to lowercase all other characters, 4) Don't modify prototype of objects you don't own

@fpg1503 2018-07-01 02:34:21

You're lowercasing the other letters, this answer is wrong.

@JC4NT 2019-04-30 19:16:22

string = string.replace(string.charAt(0), string.charAt(0).toUpperCase());

@Jack Giffin 2017-07-20 20:49:19

57 81 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 UTF32!
        return S.charAt(0).toUpperCase() + string.substring(1);
    } : function(S) {
        "use-strict";
        // the browser is using UCS16 to store UTF16
        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 UTF32!
        return S.charAt(0).toLocaleUpperCase() + string.substring(1);
    } : function(S) {
        "use-strict";
        // the browser is using UCS16 to store UTF16
        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 UTF32. However, the specification officially states that browsers are required to do everything in UTF16 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 UTF32 (like how Python uses 24-bits for each character of the string). This must seem silly to an english speaker: noone 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 stuggle 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 UTF32, 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 UTF32.

consistantCapitalizeFirstLetter works correctly in IE3+. prettyCapitalizeFirstLetter requires IE5.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 IE8- because of all the DOM and JScript bugs and lack of features in these older browsers. Further, noone uses IE3 or IE5.5 anymore.

@Semicolon 2018-12-26 10:48: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.

@Jack Giffin 2019-04-25 16:30:53

@Semicolon Thank you for pointing out a flaw with my answer. I have appended an additional explanation accordingly.

@Semicolon 2019-04-25 20:54:33

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)

@Semicolon 2019-04-25 20:55:12

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)

@Jack Giffin 2019-04-25 20:58:32

@Semicolon Thank you for your correction. I have edited the content appropriately.

@Hadnazzar 2016-06-19 18:59:52

For just capitalizing the first letter and make the rest of the string lower case:

function capitalize(str) {
     var splittedEnter = str.split(" ");
     var capitalized;
     var capitalizedResult;
     for (var i = 0 ; i < splittedEnter.length ; i++){
         capitalized = splittedEnter[i].charAt(0).toUpperCase();
         splittedEnter[i] = capitalized + splittedEnter[i].substr(1).toLowerCase();
    }
    return splittedEnter.join(" ");
}

capitalize("tHiS wiLL be alL CapiTaLiZED.");

The result will be:

This Will Be All Capitalized.

@Jaydeep Galani 2019-03-26 03:55:20

Well, all the answers will crash if the method is passed with some unexpected type of data such as Object or function.

So to ensure that it will not crash in any conditions we'll need to check for types.

capitalizeFirstLetter = string => {
  if (typeof string == "string") {
      console.log("passed");
    return string.charAt(0).toUpperCase() + string.slice(1);
  } else {
    console.log("error");
    return string;
  }
};

//type function
console.log(
  capitalizeFirstLetter(() => {
    return true;
  })
);
// error
//  () => { return true; }

//type object
console.log(capitalizeFirstLetter({ x: 1 }));
// error
// Object { x: 1 }

//type boolean
console.log(capitalizeFirstLetter(true));
// error
// true

//type undefined
console.log(capitalizeFirstLetter(undefined));
// error
// undefined

//type null
console.log(capitalizeFirstLetter(null));
// error
// null

//type NaN
console.log(capitalizeFirstLetter(NaN));
// error
// NaN

//type number
console.log(capitalizeFirstLetter(2));
// error
// 2

//type any for e.g. class
class Jaydeep {}
console.log(capitalizeFirstLetter(new Jaydeep()));
// error
// Object {}

//type string
console.log(capitalizeFirstLetter("1"));
console.log(capitalizeFirstLetter("a"));
console.log(capitalizeFirstLetter("@"));
console.log(capitalizeFirstLetter(""));
// 1
// A
// @
//  :empty string

@Jackkobec 2019-02-23 09:02:01

The simplest solution is:

let yourSentence = 'it needs first letter upper case';

yourSentence.charAt(0).toUpperCase() + yourSentence.substr(1);

or:

yourSentence.charAt(0).toUpperCase() + yourSentence.slice(1);

or:

yourSentence.substr(0, 1).toUpperCase() + yourSentence.substr(1);

@alejoko 2019-02-14 10:20:53

I prefer use a solution oriented to a functional way (mapping array for examp.):

Array.from(str).map((letter, i) => i === 0 ? letter.toUpperCase() : letter ).join('');

@Mradul Pandey 2019-01-14 15:38: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 [email protected]#$%^&*()}{{[];':",.<>/? .

@Semicolon 2018-12-26 10:33:51

I didn’t see any mention in the existing answers of issues related to astral plane codepoints 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 codepoints. 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, codepoints 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 do not access characters or codepoints. 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 to codepoints for the codepoints in two ranges, U+0 to U+D7FF and U+E000 to U+FFFF. 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 codepoints*. So for example, we can do this:

function capitalizeFirstLetter([ first, ...rest ]) {
  return [ first.toUpperCase(), ...rest ].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("𐐶𐐲𐑌𐐼𐐲𐑉") // "𐐎𐐲𐑌𐐼𐐲𐑉"

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, and while the German eszett never begins a word (afaik), it means lowercasing from "SS" in German requires additional knowledge (it could be "ss" or it could be "ß", depending on the word).

The most famous example of this issue, 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, ...rest ], locale) {
  return [ first.toLocaleUpperCase(locale), ...rest ].join('');
}

capitalizeFirstLetter("italya", "en") // "Italya"
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 with Object(element.closest('[lang]')).lang || YOUR_DEFAULT_HERE.


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!


* or surrogate code units, if orphaned

** 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.

@Akitha_MJ 2018-12-23 02:35:32

For TypeScript

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

@Alireza 2017-05-14 08:12:22

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 {
    text-transform:capitalize;
}

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'

@Kamil Kiełczewski 2018-09-19 06:21:33

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

for s='foo bar' we get

'Foo bar'

@Little Roys 2018-11-08 08:31:26

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

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

result:

'Foo'

@Wade Hatler 2019-01-11 00:14:44

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.

@Benny Powers 2018-08-10 13:42:51

A functional approach

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

Then you could

const titleCase = str => 
  str
    .split(' ')
    .map(capitalize)
    .join(' ')

@Aaron Tribou 2018-09-04 11:19:15

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.

@Thielicious 2018-08-07 16:54:01

a.slice(0,1).toUpperCase()+a.slice(1)

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

@bajran 2018-07-15 06:52:54

To make first Letter of String Capital

1st Solution

"this is a test" -> "This is a test"

var word = "this is a test"
word[0].toUpperCase();

It will give => "This is a test"

2nd Solution to make first word of string capital

"this is a test" -> "This Is A Test"

function capitalize(str) {

    const word = [];

    for(let char of str.split(' ')){
        word.push(char[0].toUpperCase() + char.slice(1))
    }

    return word.join(' ');

}

 capitalize("this is a test");

It will give => "This Is A Test"

@Melih Yıldız' 2018-09-10 12:05:09

In JS, strings are immutable.

@Wolf 2018-07-14 19:40:37

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 necessary.

@Cristian Traìna 2019-04-29 18:01:22

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

@Ilyas karim 2018-07-01 11:53:08

You can do something like this:

mode =  "string";
string = mode.charAt(0).toUpperCase() + mode.substr(1,mode.length).toLowerCase();
console.log(string);

This will print

String

@Nicolò 2015-03-09 18:22:56

function capitalize(string) {
    return string.replace(/^./, Function.call.bind("".toUpperCase));
}

@henhen 2018-06-25 19:09:16

this capitalizes the whole string

@Martin Burch 2018-06-28 16:51:24

@henhen no, the regex character ^ asserts position at start. then . matches a single character

@alejandro 2013-07-19 18:17:51

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();
}
capitalize("alfredo")  // => "Alfredo"
capitalize("Alejandro")// => "Alejandro
capitalize("ALBERTO")  // => "Alberto"
capitalize("ArMaNdO")  // => "Armando"

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

@Carlos Muñoz 2014-07-01 19:31:00

"...but not change the case of any of the other letters". This is not a correct answer to the question the OP asked.

@TMH 2014-09-05 08:25:33

@CarlosMuñoz if you read the opening sentence he says this is for a different case.

@Carlos Muñoz 2014-09-05 13:38:38

@TomHart That's exactly why it's not a solution for the question. It should be a comment or another question and answer

@TMH 2014-09-05 13:43:21

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.

@victorhazbun 2018-06-04 03:28:28

This one is simple

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

@Sterling Bourne 2018-03-19 15:32:24

This is the 2018 ES6+ 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

@Przemek 2018-06-04 08:40:50

.slice() is slower than .substring(), str[0] would be undefined for an empty string and using template literals to join the two parts introduces in here 8 characters, while + would introduce only 3.

@Sterling Bourne 2018-06-05 14:03:05

The point of my answer Prz is to showcase the new ES6 supported features, specifically template literals which was not mentioned in other posts. The idea of StackOverflow is to give the searcher “options”. They can take the concept of Template Literals described in this answer and combine it with micro-speed enhancements like Substring v. Slice if their application requires those extra saved milliseconds. My answer also doesn’t include any Unit Testing, which goes to show that you should never copypaste a StackOverflow answer directly. I assume the developer will take my answer and adapt it.

@Shivam Gupta 2018-04-30 17:12:37

Here is the nice and cleaner version;

var str = '';
return str.replace(new RegExp('^'+str[0]+''), str[0].toUpperCase());

Results:

this is a test --> This is a test

@BILAL AHMAD 2017-09-13 21:50:54

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

@Steve Harrison 2009-06-22 08:30:38

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

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

@Svish 2010-06-30 13:23:12

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

@mplungjan 2011-07-06 13:07:05

substring is understood in more browsers than substr

@Ross 2012-10-24 23:36:15

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?

@Crisfole 2013-01-04 19:41:48

Curious: is there a particular reason you use charAt rather than the indexer to get the first character?

@Crisfole 2013-01-04 19:42:38

Nevermind...""[0].toUpperCase() fails

@user656925 2013-04-12 16:18:02

@Chrisopther - charAt is faster than []

@hasen 2014-01-30 17:58:43

Shouldn't we also toLowerCase the slice(1) ?

@ban-geoengineering 2014-08-02 10:24:13

No, because the OP gave this example: the Eiffel Tower -> The Eiffel Tower. Plus, the function is called capitaliseFirstLetter not capitaliseFirstLetterAndLowerCaseAllTheOthers.

@LOGMD 2014-10-27 14:03:09

what if the char at 0 is a space?

@NemoStein 2015-02-06 22:24:08

@LOGMD Nice catch! In that case you need to trim the strim before: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

@LasagnaAndroid 2015-02-23 03:42:57

Does charAt(n) have better compatibility than treating a string as an array? Because it could easily be done like this 'string'[0] and save 7 characters lol

@dperjar 2015-03-31 16:04:21

The toLocaleUpperCase() method returns the calling string value converted to upper case, according to any locale-specific case mappings. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

@kcho0 2015-04-30 05:09:04

@hasen For LowerCase the rest of string I use the next: this.charAt(0).toUpperCase() + (this.slice(1).toString().toLowerCase());

@Jabba 2015-11-03 20:11:57

@ban-geoengineering: in Python for instance "jAVAScript".capitalize() returns 'Javascript', i.e. uppercase the first letter and lowercase the rest.

@dr.dimitru 2015-12-09 09:00:17

Nobody cares about important rule of OOP? - Never edit objects you don't own?. BTW, this one-liner looks much more elegant: string[0].toUpperCase() + string.substring(1)

@caub 2016-02-05 09:12:23

calling a var string is probably not the best idea, syntax highlighter is also confused

@Dan Cron 2016-07-22 17:31:46

@dr.dimitru: Your solution does not work with an empty string as input. Try this instead: string && string[0].toUpperCase() + string.slice(1). Fiddle

@zatamine 2016-07-29 15:23:31

It's don't work withe str = "a clash of KINGS";

@B T 2016-10-03 04:52:43

Do NOT modify the prototype of native objects. It will bite you in the ass, as it has for me.

@George Jempty 2017-10-19 13:11:15

@mplungjan I haven't had a problem using substr in my nearly 20 years of Javascript coding (that's right, going back to when VBScript was a viable alternative in IE)

@mplungjan 2017-10-19 13:23:37

@GeorgeJempty I go back a little longer than that. And there were versions of browsers that puked on substr. Enough for me to never use it

@Ray Foss 2017-11-03 15:52:05

For bigger projects, lodash has upperFirst ` _.upperFirst('fred'); // => 'Fred'`

@David R Tribble 2018-03-07 16:53:40

Needs a test: if (string && string.length > 0) ...

@Felipe Marques 2018-03-21 01:13:03

this is my solution using jQuery + input element: ` $('#firstName').on('keyup', function(ev){ ev.preventDefault(); var str = $(this).val().toLowerCase(); var strAux = []; $(str.split(' ')).each(function(i, el){ strAux.push( el.charAt(0).toUpperCase() + el.slice(1) ); }); str = strAux.join(' '); $(this).val( str ); }); `

@Anderson Marques 2018-04-03 16:29:00

In order to capitalize only the first letter even if the word is all uppercase use: return string.charAt(0).toUpperCase() + string.toLowerCase.slice(1);

@Wojtek 2018-05-21 17:10:49

ES6 one liner: const capitalize = string => `${string.charAt(0).toUpperCase()}${string.slice(1)}`;

@Lawrence Cherone 2018-05-23 20:46:36

Casting to string e.g: String(str).charAt(0).toUpperCase() + String(str).slice(1) allows for boolean values to be ucfirst as well.

@Akitha_MJ 2018-12-23 02:33:18

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

@El Abogato 2019-02-06 10:40:43

Hi, I am very surprised this is the best answer. This does not work in all cases. if your input text is "HELLO", uppercasing the first letter, will result in the same text. You should first downcase the whole string and afterwards perform the action mentioned in this answer. Otherwise is not an always working solution.

@Cristian Traìna 2019-04-29 17:49:01

I think the best solution is string.replace(/./, w => w.toUpperCase()), taking advantage of ES5 arrow functions. Too bad many people will just open the page and copy/paste the first answer. It also works on empty strings

@Rambabu Bommisetti 2018-02-14 12:03:21

var a = "this is a test"
console.log(a.replace(/^[a-z]/g, txt => txt.toUpperCase()));

@Aditya Joshi 2018-01-30 19:21:14

One liner("inputString can be set to any string") inputString.replace(/.{1}/ ,inputString.charAt(0).toUpperCase())

@noahnu 2018-01-30 19:52:07

charAt accepts an optional numeric index as an argument, not a pattern. Using RegEx here seems unnecessarily expensive. Also the correct version of this has already been posted here.

@Aditya Joshi 2018-01-30 22:09:56

@noahnu it working fine. tested it.

@Aditya Joshi 2018-01-30 22:21:56

@noahnu there was typo and there are many way to solve the same thing

@noahnu 2018-01-30 22:27:21

reason it worked is because the charAt argument was 'sanitized'. It went from /.{1}/ -> NaN -> 0. What I meant by "correct", was the version you just edited your answer to. If you follow the link I provided, another user already posted your approach in 2015, meaning your answer doesn't add anything.

@Aditya Joshi 2018-01-31 23:24:01

@noahnu i recently got in to posting solution or alternate solution to a problem recently, earlier i used to ask mostly. Much respect from fellow programmer .

@Qwerty 2018-01-22 18:27:10

You can do it in one line like this

string[0].toUpperCase() + string.substring(1)

@Dan Dascalescu 2019-01-27 22:11:28

This answer was already given in 2009.

@Puiu 2018-01-22 18:09:48

For thoroughness, adding another way that I did not see mentioned. Just because you can, doesn't mean you should however. Requires ES6 as code uses array destructuring.

const capitalizeFirstLetter = s => {
  const type = typeof s;
  if (type !== "string") {
    throw new Error(`Expected string, instead received ${type}`);
  }

  const [firstChar, ...remainingChars] = s;

  return [firstChar.toUpperCase(), ...remainingChars].join("");
};

Related Questions

Sponsored Content

38 Answered Questions

[SOLVED] How do I remove a property from a JavaScript object?

86 Answered Questions

[SOLVED] How do JavaScript closures work?

53 Answered Questions

[SOLVED] How to replace all occurrences of a string in JavaScript

3 Answered Questions

33 Answered Questions

[SOLVED] For-each over an array in JavaScript?

14 Answered Questions

[SOLVED] Convert JavaScript String to be all lower case?

  • 2008-09-30 20:22:35
  • Derek
  • 413824 View
  • 1223 Score
  • 14 Answer
  • Tags:   javascript string

79 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 5716182 View
  • 7108 Score
  • 79 Answer
  • Tags:   javascript arrays

36 Answered Questions

[SOLVED] Creating multiline strings in JavaScript

28 Answered Questions

[SOLVED] Random string generation with upper case letters and digits

  • 2010-02-13 12:23:58
  • Hellnar
  • 759621 View
  • 1168 Score
  • 28 Answer
  • Tags:   python string random

54 Answered Questions

[SOLVED] How do I include a JavaScript file in another JavaScript file?

Sponsored Content