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

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

@Mohamed Ben Hartouz 2019-07-18 15:59:50

The method will take a value and then split it to have an array of string.

const firstLetterToUpperCase = value => {
 return value.replace(
    value.split("")["0"], // Split stirng and get the first letter 
    value
        .split("")
        ["0"].toString()
        .toUpperCase() // Split string and get the first letter to replace it with an uppercase value
  );
};

@Tyson Phalp 2019-07-18 17:14:28

Could you add details about what the above code does? That would be really useful, and would increase the quality of your answer.

@Mohamed Ben Hartouz 2019-07-19 21:42:09

yeah okay, i will do that

@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

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

@pizzamonster 2015-04-08 20:09:42

The currently voted answer is right, but it doesn't trim or check the length of the string before capitalising the first character.

String.prototype.ucfirst = function(notrim) {
    s = notrim ? this : this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'').replace(/\s+/g,' ');
    return s.length > 0 ? s.charAt(0).toUpperCase() + s.slice(1) : s;
}

Set the notrim argument to prevent trimming the string first:

'pizza'.ucfirst()         => 'Pizza'
'   pizza'.ucfirst()      => 'Pizza'
'   pizza'.ucfirst(true)  => '   pizza'

@Peter Mortensen 2019-06-13 23:14:49

What do you mean by "The currently voted answer"? Do you mean "The currently highest voted answer"?

@pizzamonster 2019-06-14 22:43:31

@PeterMortensen: sorry, I answered this in 2015 and guess I was referring to the accepted answer but I can't remember. Feel free to change/correct.

@Mr. X 2015-03-07 15:57:55

I use something along these lines in my development environment, especially when working with APIs like HTTP:

Suppose you have an HTTP header in which you'd like to capitalize every initial letter in its name and add the hyphen between its constituent words. You may achieve something like that using this basic and simple routine:

'access control allow origin'
    .replace(/\b\w/g, function (match) {
        return match.toUpperCase();
    })
    .split(' ')
    .join('-');

// Output: 'Access-Control-Allow-Origin'

It is not maybe the most elegant and attractive function definition out there, but it certainly gets the job done.

@mfq 2014-12-24 16:11:55

Use this module of Node.js, the http://stringjs.com/ package, to capitalize your string:

var S = require('string');
S('jon').capitalize().s; //'Jon'
S('JP').capitalize().s; //'Jp'

@Craicerjack 2015-06-11 12:21:15

So you need to install node and a package to capitalise a string. Bit of overkill.

@AMIC MING 2014-09-25 16:13:48

Use:

var str = "ruby java";

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

It will output "Ruby java" to the console.

@Gabriel Hautclocq 2014-02-06 14:06:16

Here is my attempt to make a universal function that can capitalize only the first letter, or the first letter of each word, including words separated by a dash (like some first names in French).

By default, the function capitalizes only the first letter and leave the rest untouched.

Parameters:

  • lc: true to lowercase the rest of the word(s)
  • all: true to capitalize each word

 

if (typeof String.prototype.capitalize !== 'function') {
    String.prototype.capitalize = function(lc, all) {
        if (all) {
            return this.split( " " ).map( function(currentValue, index, array ) {
                return currentValue.capitalize( lc );
            }, this).join(" ").split("-").map(function(currentValue, index, array) {
                return currentValue.capitalize(false);
            }, this).join("-");
        }
        else {
            return lc ? this.charAt(0).toUpperCase() + this.slice(1 ).toLowerCase() : this.charAt(0).toUpperCase() + this.slice(1);
        }
    }
}

@Lukas 2014-04-04 06:51:32

jQuery to update user's input capitalized: $('.on-change-capitalize').change(function(){ $(this).val($(this).val().capitalize(true, true)); }); btw, it also works with utf8 chars ;) thanks!

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

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

Just because you can, doesn't mean you should, however. It requires ECMAScript 6 as the 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("");
};

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

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

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

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

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

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

@Code Maniac 2019-07-06 05:56:38

Using /^[a-z]/i will be better than using . as the prior one will not try to replace any character other than alphabets

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

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

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

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

@Adam R. Turner 2019-06-21 19:17:31

You can return directly Webwoman, it would be like this: function capitalize(str) { return str.charAt(0).toUpperCase() + str.slice(1); }

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

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

@Fernando Paz 2019-06-02 11:47:08

This does the trick, why was it downvoted with no explanation at all?

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

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

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

Related Questions

Sponsored Content

3 Answered Questions

79 Answered Questions

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

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

37 Answered Questions

[SOLVED] Creating multiline strings in JavaScript

56 Answered Questions

[SOLVED] How to replace all occurrences of a string?

57 Answered Questions

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

27 Answered Questions

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

  • 2010-02-13 12:23:58
  • Hellnar
  • 783876 View
  • 1205 Score
  • 27 Answer
  • Tags:   python string random

38 Answered Questions

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

86 Answered Questions

[SOLVED] How do JavaScript closures work?

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
  • 421265 View
  • 1243 Score
  • 14 Answer
  • Tags:   javascript string

Sponsored Content