5115

How do I make the first character of a string uppercase if it's a letter, 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"
miken32
  • 42,008
  • 16
  • 111
  • 154
Robert Wills
  • 51,811
  • 3
  • 18
  • 6
  • 21
    [Underscore](http://underscorejs.org) has a plugin called [underscore.string](https://github.com/epeli/underscore.string) that includes this and a bunch of other great tools. – Aaron Apr 15 '13 at 19:16
  • 3
    For those using angular, there is a titlecase pipe: https://angular.io/api/common/TitleCasePipe – ecstrema Jan 27 '21 at 20:54
  • 3
    For those who don't know how Stack Overflow is designed to work: Resolving advice is posted to the page as an "answer". Any non-resolving advice, requests for clarity, and lone/relevant hyperlinks can be posted as comments under the question. – mickmackusa Jun 16 '21 at 23:17

102 Answers102

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

TylerH
  • 20,799
  • 66
  • 75
  • 101
Steve Harrison
  • 121,227
  • 16
  • 87
  • 72
  • Here's this solution in TypeScript, where the type returned is the capitalized word, rather than `string`: `const capitalize = (s: T) => (s[0].toUpperCase() + s.slice(1)) as Capitalize;` – Dan Tello Mar 27 '23 at 17:56
1622

Edited to add this DISCLAIMER: please read the comments to understand the risks of editing JS basic types.


Here's a more object-oriented approach:

Object.defineProperty(String.prototype, 'capitalize', {
  value: function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
  },
  enumerable: false
});

You'd call the function, like this:

"hello, world!".capitalize();

With the expected output being:

"Hello, world!"
Eduardo Russo
  • 4,121
  • 2
  • 22
  • 38
Steve Hansell
  • 17,465
  • 1
  • 17
  • 14
  • 62
    @NielsLucas Fair enough. It has the potential to break future additions to JS. If it's code that only you will use, then it's not so bad - you just update your code and move on. The real issue here is when you start publishing libraries with code like this: your code modifies the built-in behavior for every library using your code. The consequence is that if you and another library author both override the same built-ins with your own implementations, you create bugs in the other library's code (or whichever is loaded last) leaving the user with debugging hell of unreproducible bug reports. – aggregate1166877 Jul 01 '21 at 03:52
  • 3
    @aggregate1166877 Thank you for the explanation. I totally agree with you that this way is NOT gonna be a good practice for creating a library and I also agree that this way is fine for a project. Hope people will read this, cause I think this is a good attention to the original answer. – Niels Lucas Jul 01 '21 at 13:59
  • 2
    sorry but no, just don't add any functions to basic types. extend them ? const ExtendedString = class extends String { capitalize () { return this[0].toUpperCase() + this.slice(1) } } const s = new ExtendedString('hello') console.log(s.capitalize()) – Martijn Scheffer Oct 26 '21 at 14:01
  • 2
    It would be great to see the author include some of this disclaimer and detail about extending built-in types in the post. Hard for people to notice the comments. – brandonscript Dec 13 '21 at 16:50
1028

In CSS:

p::first-letter {
    text-transform:capitalize;
}
InSync
  • 4,851
  • 4
  • 8
  • 30
sam6ber
  • 10,889
  • 1
  • 13
  • 3
  • 172
    $('#mystring_id').text(string).css('text-transform','capitalize'); – DonMB Sep 24 '15 at 17:34
  • 47
    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. – dmansfield Jun 07 '16 at 13:26
  • 11
    Also `::first-letter` works ONLY on elements with a `display` value of `block`, `inline-block`, `table-cell`, `list-item` or `table-caption`. In all other cases, `::first-letter` has no effect. – Dzmitry Kulahin Dec 08 '21 at 13:11
  • ^ I am immensely curious why this doesn't work for `flex` and `grid`.... – Leland May 19 '23 at 13:01
  • Why is that even upvoted. That wasn't the question.. – Page not found Jul 15 '23 at 16:28
483

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

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

Update

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

Update 2:

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

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

ES6 version

const capitalize = s => s && s[0].toUpperCase() + s.slice(1)

// to always return type string event when s may be falsy other than empty-string
const capitalize = s => (s && s[0].toUpperCase() + s.slice(1)) || ""
InSync
  • 4,851
  • 4
  • 8
  • 30
joelvh
  • 16,700
  • 4
  • 28
  • 20
286

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

Community
  • 1
  • 1
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
262

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

Overview of the hidden problem and various approaches to it

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='', ...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) {
  if (!str) return '';

  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) {
  if (!str) return '';

  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("") // ""

Deeper into internationalization (whose capitalization?)

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='', ...rest ], locale) {
  return [ first.toLocaleUpperCase(locale), ...rest ].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 for at least some languages, though outlying cases will be hard to avoid completely if doing so no matter what the primary language is.

The CWU or Changes_When_Uppercased character property matches all code points which change when uppercased in the generic case where specific locale data is absent. There are other interesting case-related Unicode character properties that you may wish to play around with. It’s a cool zone to explore but we’d go on all day if we enumerated em all here. Here’s something to get your curiosity going if you’re unfamiliar, though: \p{Lower} is a larger group than \p{LowercaseLetter} (aka \p{Ll}) — conveniently illustrated by the default character set comparison in this tool provided by Unicode. (NB: not everything you can reference there is also available in ES regular expressions, but most of the stuff you’re likely to want is).

Alternatives to case-mapping in JS (Firefox & CSS love the Dutch!)

If digraphs with unique locale/language/orthography capitalization rules happen to have a single-codepoint “composed” representation in Unicode, these might be used to make one’s capitalization expectations explicit even in the absence of locale data. For example, we could prefer the composed i-j digraph, ij / U+133, associated with Dutch, to ensure a case-mapping to uppercase IJ / U+132:

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

On the other hand, precomposed digraphs and similar are sometimes deprecated (like that one, it seems!) and may be undesirable in interchanged text regardless due to the potential copypaste nuisance if that’s not the normal way folks type the sequence in practice. Unfortunately, in the absence of the precomposition “hint,” an explicit locale won’t help here (at least as far as I know). If we spell ijsselmeer with an ordinary i + j, capitalizeFirstLetter will produce the wrong result even if we explicitly indicate nl as the locale:

capitalizeFirstLetter('ijsselmeer', 'nl'); // "Ijsselmeer" :(

(I’m not entirely sure whether there are some such cases where the behavior comes down to ICU data availability — perhaps someone else could say.)

If the point of the transformation is to display textual content in a web browser, though, you have an entirely different option available that will likely be your best bet: leveraging features of the web platform’s other core languages, HTML and CSS. Armed with HTML’s lang=... and CSS’s text-transform:..., you’ve got a (pseudo-)declarative solution that leaves extra room for the user agent to be “smart.” A JS API needs to have predictable outcomes across all browsers (generally) and isn’t free to experiment with heuristics. The user-agent itself is obligated only to its user, though, and heuristic solutions are fair game when the output is for a human being. If we tell it “this text is Dutch, but please display it capitalized,” the particular outcome might now vary between browsers, but it’s likely going to be the best each of them could do. Let’s see:

<!DOCTYPE html>
<dl>
<dt>Untransformed
<dd>ijsselmeer
<dt>Capitalized with CSS and <code>lang=en</code>
<dd lang="en" style="text-transform: capitalize">ijsselmeer
<dt>Capitalized with CSS and <code>lang=nl</code>
<dd lang="nl" style="text-transform: capitalize">ijsselmeer

In Chromium at the time of writing, both the English and Dutch lines come out as Ijsselmeer — so it does no better than JS. But try it in current Firefox! The element that we told the browser contains Dutch will be correctly rendered as IJsselmeer there.

This solution is purpose-specific (it’s not gonna help you in Node, anyway) but it was silly of me not to draw attention to it previously given some folks might not realize they’re googling the wrong question. Thanks @paul23 for clarifying more about the nature of the IJ digraph in practice and prompting further investigation!


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.

Semicolon
  • 6,793
  • 2
  • 30
  • 38
  • I had been wondering for a while why `toUpperCase` didn't really do much for some languages... but didn't quite care enough to find out. Glad I finally did, this was a very interesting read! – Stephan Bijzitter Jul 19 '21 at 22:09
  • This doesn't seem to work with digraphs such as "IJ" in dutch. Using the latest version the example here is incorrectly capitalized to "Ijsselmeer" (The regex version). The code I used was: `capitalizeFirstLetter('ijssel', 'nl-NL')` - That's a correct localization string right? – paul23 Aug 24 '21 at 11:38
  • "ij" as U+69, U+6A would capitalize as "Ij", yes - "ij" (U+133, a single code point) is what capitalizes to "IJ" (U+132). Locale-awareness here only extends as far as the case mapping rules Unicode defines that sometimes vary per language, as in Turkish; knowing whether "ij" (U+69, U+6A) _should be interpreted as_ ij (U+133) is outside its scope and requires at minimum a dictionary for that language. – Semicolon Aug 25 '21 at 12:09
  • @paul23 You wrote `ij` (2 letters) instead of `ij` (1 letter). – CherryDT Jun 06 '22 at 23:01
  • 2
    In netherlands dutch IJ is considered 2 letters, which are just capitalized at the same time (in contrary to the belgian version). – paul23 Jun 23 '22 at 16:52
  • That’s very interesting paul23 — love that sort of concept-of-what-counts-as-a-letter-can-itself-differ twist! Though this Netherlands Dutch vs Belgian distinction seems like a pretty good illustration of how situations can arise where additional information sources & ICU data may be needed, it also suggests my use of it as an example in the answer (especially with the name of a location in the Netherlands) might be more confusing than helpful. Do you think it should be changed? – Semicolon Aug 24 '22 at 17:12
  • @paul23, I went ahead and updated it. If you see this, lemme know if that’s better! – Semicolon Aug 24 '22 at 18:49
170

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();
alejandro
  • 2,799
  • 1
  • 17
  • 25
98

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

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

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

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

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

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

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

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

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

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

Vanilla JavaScript for first upper case:

function upperCaseFirst(str){
    return str.charAt(0).toUpperCase() + str.substring(1);
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
chovy
  • 72,281
  • 52
  • 227
  • 295
  • 16
    I think the preference should be for vanilla Js as most people will not download an entire framework only to capitalize a string. – GGG Dec 06 '15 at 23:49
  • 8
    In all my projects so far I've never used lodash. Don't forget either that most people on google will end on this page, and listing a framework as an alternative is fine, but not as a main answer. – GGG Dec 08 '15 at 14:44
  • @GGG In all my projects so far I've used lodash – Hemerson Varela Jun 24 '21 at 13:31
  • 1
    Vanilla js is better than lodash. Nobody uses it anymore. – chovy Jun 26 '21 at 06:59
  • 9
    @chovy I looked it up on npm and it has ~40,276,984 downloads within the past week and is a dependent of ~144k packages. I wouldn't say nobody uses it. – Script47 Sep 22 '21 at 23:02
97

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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sterling Bourne
  • 3,064
  • 23
  • 22
81

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

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

Result:

'Foo'
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Little Roys
  • 5,383
  • 3
  • 30
  • 28
  • 2
    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. – Wade Hatler Jan 11 '19 at 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 – Code Maniac Jul 06 '19 at 05:56
  • 7
    @CodeManiac there are so many languages and letters except [a-z] – msdos Sep 11 '21 at 23:20
68

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

Remarks

  • 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

InSync
  • 4,851
  • 4
  • 8
  • 30
Przemek
  • 3,855
  • 2
  • 25
  • 33
  • 2
    You actually don't want to use the plus sign (+) as a concatenation method in ES6. You'll want to use template literals: https://eslint.org/docs/rules/prefer-template – Sterling Bourne Mar 19 '18 at 15:37
66

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(" ");
}
GAMITG
  • 3,810
  • 7
  • 32
  • 51
Dan
  • 773
  • 5
  • 2
  • 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.** – JimmyPena Nov 30 '11 at 19:13
  • 2
    I know I did. I'd add one thing, in case the entire string starts capitalized: pieces[i] = j + pieces[i].substr(1).toLowerCase(); – Malovich Dec 20 '12 at 21:16
  • 5
    Another solution to this case: function capitaliseFirstLetters(s) { return s.split(" ").map(function(w) { return w.charAt(0).toUpperCase() + w.substr(1) }).join(" ") } Can be a nice one-liner if it's not put into a function. – Luke Channings Mar 10 '13 at 21:36
  • Would be better to first lowercase the whole string – Magico Jul 06 '16 at 10:36
  • 1
    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(' ')` – OverCoder Jul 28 '17 at 18:10
60

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'
capitalizeTxt('dezfoolian');  // return 'Dezfoolian'

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'
InSync
  • 4,851
  • 4
  • 8
  • 30
Alireza
  • 100,211
  • 27
  • 269
  • 172
56
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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254
  • 6
    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. – dudewad Feb 22 '17 at 01:08
  • The other ES6 answer is simpler: `const capitalize = ([first,...rest]) => first.toUpperCase() + rest.join('').toLowerCase();`. – Dan Dascalescu Jun 22 '19 at 05:50
  • 1
    @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. – Someone Special Jan 25 '21 at 10:56
52

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()) );
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
51

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.

SK-the-Learner
  • 523
  • 5
  • 18
Robert Wills
  • 51,811
  • 3
  • 18
  • 6
  • 9
    @999: where does it say that `substr()` is deprecated? [It's not](http://code.google.com/p/closure-compiler/issues/detail?id=285), even now, three years later, let alone back in 2009 when you made this comment. – Dan Dascalescu Nov 07 '12 at 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". – Peter Rust Nov 21 '12 at 22:05
  • 3
    Having 3 methods that do the same thing (`substring`, `substr` and `slice`) is too many, IMO. I always use `slice` because it supports negative indexes, it doesn't have the confusing arg-swapping behavior and its API is similar to `slice` in other languages. – Peter Rust Nov 21 '12 at 22:12
51

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

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

And for all coffee-junkies:

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

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

var capitalize = function (input) {
  return input.replace(/^./, function (match) {
    return match.toUpperCase();
  });
};
yckart
  • 32,460
  • 9
  • 122
  • 129
50

Use:

var str = "ruby java";

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

It will output "Ruby java" to the console.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
AMIC MING
  • 6,306
  • 6
  • 46
  • 62
48

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.

Example:

_.capitalize("foo bar") == "Foo bar"
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
andersh
  • 8,105
  • 6
  • 39
  • 30
  • 3
    Since, version [3.0.0](https://github.com/lodash/lodash/releases/tag/3.0.0), Lo-Dash has this string method available by default. Just like described in this answer: `_.capitalize("foo") === "Foo"`. – bardzusny Apr 09 '15 at 19:09
  • Also there are usefull underscore.js function called `humanize`. It converts an underscored, camelized, or dasherized string into a humanized one. Also removes beginning and ending whitespace, and removes the postfix '_id'. – Stepan Zakharov May 07 '15 at 14:11
  • 2
    From version 4*, Lodash also lowercase() every other letter, be careful! – Igor Loskutov Feb 13 '16 at 08:33
46

If you're ok with capitalizing the first letter of every word, and your usecase is in HTML, you can use the following CSS:

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

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

InSync
  • 4,851
  • 4
  • 8
  • 30
Ryan
  • 1,157
  • 7
  • 2
  • 30
    @Simon It's not stated that the string is necessarily going to be output as part of a HTML document - CSS is only going to be of use if it is. – Adam Hepton Jan 18 '12 at 09:32
  • 10
    Adam, true, but I'd guess that over 95% of the Javascript out there is used with HTML & CSS. Unfortunately, the "capitalize" statement actually capitalizes **every word**, so you'd still need JS to capitalize only the first letter of the string. – Simon East Jan 21 '12 at 04:24
  • @Simon, the text-transform capitalizes first letter of every word and this is what Robert wants – DDK Jun 25 '12 at 08:42
  • 19
    Incorrect, Dinesh. He said *the first character of the string*. – Simon East Jun 26 '12 at 00:02
  • 1
    What's funny is that Ryan didn't help answer @Robert Willis's question. but he answered mine. – SoreThumb Nov 05 '12 at 01:59
  • 85
    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](http://stackoverflow.com/badges/37/disciplined) if you delete it. **Please do so.** – Dan Dascalescu Nov 07 '12 at 06:06
  • 4
    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. – Matt Parkins Dec 01 '12 at 11:34
  • 1
    The question specifies 'JavaScript'. A CSS solution doesn't provide this. – Holf Mar 22 '13 at 18:01
  • 4
    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. – Ali Gangji Apr 13 '13 at 08:54
  • 6
    It's now javascript: $('.capitalize').css('text-transform', 'capitalize') – Ali Gangji Apr 13 '13 at 08:58
  • 1
    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. :-) – Holf May 17 '13 at 16:56
  • 1
    So just wrap the tag around the single world you want capitalized – Nick Manning Oct 04 '13 at 05:40
  • This capitalizes every word's first letter. – Michael Mikhjian Nov 20 '13 at 20:35
  • 1
    This answer is bad since it is not **JavaScript**. – ivkremer May 15 '14 at 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](http://stackoverflow.com/a/11524251/1048572) – Bergi May 18 '14 at 10:06
38
var capitalized = yourstring[0].toUpperCase() + yourstring.substr(1);
zianwar
  • 3,642
  • 3
  • 28
  • 37
38

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
GAMITG
  • 3,810
  • 7
  • 32
  • 51
monokrome
  • 1,377
  • 14
  • 21
35
String.prototype.capitalize = function(){
    return this.replace(/(^|\s)([a-z])/g, 
                        function(m, p1, p2) {
                            return p1 + p2.toUpperCase();
                        });
};

Usage:

capitalizedString = someString.capitalize();

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Murat Kucukosman
  • 634
  • 5
  • 11
  • +1, this is what I was really looking for. There is a minor bug though, it ought to be `return.this.toLocaleLowerCase().replace(` ... – tomdemuyt Jan 14 '13 at 21:55
  • +1, I found this page looking for a javascript version of phps ucfirst, which I suspect is how most people find it. – Benubird Apr 09 '13 at 13:58
  • @DanDascalescu I found this useful, so +1 utilitarianism, and -1 anal-retentiveness. He included an example, so its function is clear. – Travis Webb Aug 02 '13 at 10:24
  • 1
    `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. – IGRACH Apr 28 '14 at 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 – Przemek Sep 23 '17 at 19:32
34
function capitalize(s) {
    // returns the first letter capitalized + the string from index 1 and out aka. the rest of the string
    return s[0].toUpperCase() + s.substr(1);
}


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

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

capitalize('/index.html');
=> '/index.html'
Fredrik
  • 971
  • 8
  • 23
  • Done @Ram. Also included examples. – Fredrik Jul 23 '15 at 13:14
  • How is this any better than [the 2009 answer](https://stackoverflow.com/a/1026087/1269037)?. – Dan Dascalescu Jan 27 '19 at 22:13
  • 1
    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 ;) – Fredrik Jun 20 '19 at 11:50
33
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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Wolf
  • 567
  • 7
  • 10
  • 5
    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 – Christian Vincenzo Traina Apr 29 '19 at 18:01
  • This is a good answer! There is a small caveat: `\w Matches any alphanumeric character from the basic Latin alphabet, including the underscore.` so replacing a word like `_boss` will yield `_boss` (from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes#types) – Șerban Ghiță May 05 '22 at 17:25
  • @ȘerbanGhiță The same would apply to `1boss`. If matching an underscore is not the desired behaviour, use `[A-Za-z-0-9]` or `[^\W_]`. – InSync May 19 '23 at 22:35
31

A Solution That Works For All Unicode Characters

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 UTF-32!
        return S.charAt(0).toUpperCase() + S.substring(1);
    } : function(S) {
        "use-strict";
        // 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() + S.substring(2) :
            S.charAt(0).toUpperCase() + S.substring(1)
        );
    };
const prettyCapitalizeFirstLetter = "\uD852\uDF62".length === 1 ?
    function(S) {
        "use-strict"; // Hooray! The browser uses UTF-32!
        return S.charAt(0).toLocaleUpperCase() + S.substring(1);
    } : function(S) {
        "use-strict";
        // 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() + S.substring(2) :
            S.charAt(0).toLocaleUpperCase() + S.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+ (when the const is changed to var). 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.

InSync
  • 4,851
  • 4
  • 8
  • 30
Jack G
  • 4,553
  • 2
  • 41
  • 50
  • 2
    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. – Semicolon Dec 26 '18 at 10:48
  • 1
    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 Apr 25 '19 at 20:54
  • 1
    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) – Semicolon Apr 25 '19 at 20:55
  • Wow—almost 5 years old and lots of edits. It looks really useful, but this code has clearly never been run. `S` or `string`? – dsl101 Feb 11 '22 at 14:29
  • While you're possibly correct that no other answers (at the time of your posting) dealt with these characters correctly, the question *also* didn't ask for this. – Kevin B Feb 07 '23 at 19:11
30
var str = "test string";
str = str.substring(0,1).toUpperCase() + str.substring(1);
MD SHAHIDUL ISLAM
  • 14,325
  • 6
  • 82
  • 89
21
yourString.replace(/^[a-z]/, function(m){ return m.toUpperCase() });

EDIT: Regexp is overkill for this, prefer the simpler : str.charAt(0).toUpperCase() + str.substring(1)

Simon
  • 2,067
  • 2
  • 17
  • 30
  • 5
    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: http://forwebonly.com/capitalize-the-first-letter-of-a-string-in-javascript-the-fast-way/ – Robin van Baalen Feb 13 '13 at 13:17
  • 1
    Regexp is overkill for this, prefer the simpler : str.charAt(0).toUpperCase() + str.slice(1) – Simon Jan 23 '17 at 13:36
  • 1
    Often times, if you want to solve your problem with regex, you end up with two problems. – Przemek Sep 23 '17 at 19:18
21

Check out this solution:

var stringVal = 'master';
stringVal.replace(/^./, stringVal[0].toUpperCase()); // Returns Master
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Raju Bera
  • 948
  • 8
  • 14
  • 3
    Save some keystrokes ;) `stringVal.replace(/^./, stringVal[0].toUpperCase());` – Alfredo Delgado Oct 15 '15 at 19:30
  • 2
    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. – Przemek Sep 23 '17 at 19:28
21

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

text-transform: capitalize;

div.text-capitalize {
  text-transform: capitalize;
}
<h2>text-transform: capitalize:</h2>
<div class="text-capitalize">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
Dory Daniel
  • 798
  • 14
  • 21
Deen John
  • 3,522
  • 4
  • 29
  • 32
20

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)}`;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Christian Matthew
  • 4,014
  • 4
  • 33
  • 43
20

with arrow function

let fLCapital = s => s.replace(/./, c => c.toUpperCase())
fLCapital('this is a test') // "This is a test"

with arrow function, another solution

let fLCapital = s => s = s.charAt(0).toUpperCase() + s.slice(1);
fLCapital('this is a test') // "This is a test"

with array and map()

let namesCapital = names => names.map(name => name.replace(/./, c => c.toUpperCase()))
namesCapital(['james', 'robert', 'mary']) // ["James", "Robert", "Mary"]
Ahmad Moghazi
  • 1,419
  • 13
  • 15
18

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"
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
a8m
  • 9,334
  • 4
  • 37
  • 40
18

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.

GAMITG
  • 3,810
  • 7
  • 32
  • 51
raphie
  • 3,285
  • 2
  • 29
  • 26
18

You can do it in one line like this

string[0].toUpperCase() + string.substring(1)
Qwerty
  • 1,252
  • 1
  • 11
  • 23
14

A functional approach

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

Then you could

const titleCase = str => 
  str
    .split(' ')
    .map(capitalize)
    .join(' ')
Andrii Malykhin
  • 137
  • 1
  • 6
Benny Powers
  • 5,398
  • 4
  • 32
  • 55
  • 2
    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. – Aaron Tribou Sep 04 '18 at 11:19
13

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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Omar bakhsh
  • 896
  • 11
  • 18
  • first char of word to upper case = word[0].toUpperCase() skipe first char and lower rest = slice(1).toLowerCase(); – Omar bakhsh Jul 19 '20 at 01:10
  • 1
    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_?" – Sean Aug 22 '20 at 20:28
  • you can ignore the other extra step of code : +word.slice(1).toLowerCase(); – Omar bakhsh Aug 23 '20 at 00:17
12

In CoffeeScript, add to the prototype for a string:

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

Usage would be:

"woobie".capitalize()

Which yields:

"Woobie"
Martin
  • 2,302
  • 2
  • 30
  • 42
longda
  • 10,153
  • 7
  • 46
  • 66
  • 12
    This is a JavaScript question. – Cobby May 06 '14 at 00:54
  • 15
    @Cobby - And this is a coffeescript answer. – longda May 06 '14 at 19:29
  • I think what Cobby is trying to say that some idiots are trying to accomplish every simple JavaScript task using stupid libraries while the very same solution in vanilla is as simple as `String.prototype.capitalize = function () { return this.substring(0,1).toUpperCase() + this.substring(1).toLowerrCase() }` – Shiala Jul 16 '14 at 17:17
  • 2
    Coffeescript is a preprocessor language, not a library... A library for this would be silly – TaylorMac Jul 30 '14 at 20:18
  • 4
    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: http://coffeescript.org/ – longda Jul 30 '14 at 23:28
12

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);
ilter
  • 4,030
  • 3
  • 34
  • 51
  • I would go `str = str.charAt(0).toLocaleUpperCase() + str.substr(1);`, though, to make this shorter – YakovL Dec 28 '17 at 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? – Peter Mortensen Jan 06 '21 at 23:23
12

CoffeeScript

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

As a String prototype method:

String::capitalize = -> @charAt(0).toUpperCase() + @slice(1)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Łukasz Kurowski
  • 340
  • 6
  • 18
11
function capitalize(string) {
    return string.replace(/^./, Function.call.bind("".toUpperCase));
}
Nicolò
  • 1,795
  • 1
  • 16
  • 16
11

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())
Tim
  • 1,105
  • 13
  • 14
10
// Uppercase first letter
function ucfirst(field) {
    field.value = field.value.substr(0, 1).toUpperCase() + field.value.substr(1);
}

Usage:

<input type="text" onKeyup="ucfirst(this)" />
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Pnobuts
  • 143
  • 1
  • 8
  • 3
    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. – abestic9 May 17 '13 at 02:29
10

Here are a few suggestions 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 or other separators (like some first names in French).

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

Parameters:

  • lc: true to force lower-casing the rest of the word(s)
  • all: true to capitalize each word

1. No regex version

function capitalize( str, lc, all ) {
    if( all ) {
        return str.split( " " )
            .map( word => capitalize( word, lc ) )
            .join( " " )
            .split( "-" )
            .map( word => capitalize( word, false ) )
            .join( "-" );
    } else {
        return lc
            ? str.charAt( 0 ).toUpperCase() + str.slice( 1 ).toLowerCase()
            : str.charAt( 0 ).toUpperCase() + str.slice( 1 );
    }
}

2. Using regex

function capitalize( str, lc, all ) {
    const replacer = ( m, p1, p2 ) =>
        p1.toUpperCase() + ( lc ? p2.toLowerCase() : p2 );
    if( all ) {
        return str.split( /(\s|-|')/ )
                  .map( s => s.replace( /^([a-z])(.*)$/, replacer ) )
                  .join( "" )
    } else {
        return str.replace( /^([a-z])(.*)$/, replacer )
    }
}

3. Alternative with rest parameters

function capitalizeWord( [first, ...rest], lc ) {
    return first.toUpperCase() + ( lc ? rest.join("").toLowerCase() : rest.join("") );
}
function capitalize( str, lc, all ) {
    return all ? str.split( /(\s|-|')/ )
                    .map( s => capitalizeWord( s, lc ) )
                    .join( "" )
               : capitalizeWord( str, lc );
}

Examples

capitalize( "saiNT-jEAn d'anGÉly", false, false )
// returns "SaiNT-jEAn d'anGÉly"

capitalize( "saiNT-jEAn d'anGÉly", false, true )
// returns "SaiNT-JEAn D'AnGÉly"

capitalize( "saiNT-jEAn d'anGÉly", true, false )
// returns "Saint-jean d'angély"

capitalize( "saiNT-jEAn d'anGÉly", true, true )
// returns "Saint-Jean D'Angély"
Gabriel Hautclocq
  • 3,230
  • 2
  • 26
  • 31
  • 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! – Lukas Liesis Apr 04 '14 at 06:51
10

Capitalize and Uncapitalize first Char of a String.

Functions to include:

/** First Character uppercase */
function capitalize(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
}

/** First Character lowercase */
function uncapitalize(str) {
    return str.charAt(0).toLowerCase() + str.slice(1);
}

Example1 "First Character uppercase":

alert(capitalize("hello world"));

Result: Hello world

Example 2 "First Character lowercase":

alert(uncapitalize("Hello World, today is sunny"));

Result: hello World, today is sunny

9

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Zaheer Ahmed
  • 28,160
  • 11
  • 74
  • 110
9

Or you could use Sugar.js capitalize()

Example:

'hello'.capitalize()           -> 'Hello'
'hello kitty'.capitalize()     -> 'Hello kitty'
'hello kitty'.capitalize(true) -> 'Hello Kitty'
andersh
  • 8,105
  • 6
  • 39
  • 30
9

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"));
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
BILAL AHMAD
  • 686
  • 6
  • 14
9
s[0].toUpperCase``+s.substr`1`

let s = 'hello there'

console.log( s[0].toUpperCase``+s.substr`1` )
Thielicious
  • 4,122
  • 2
  • 25
  • 35
9

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

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

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

Jakub Januszkiewicz
  • 4,380
  • 2
  • 37
  • 54
  • `String.prototype.capitalize = String.prototype.capitalize || function() { var first = this.substring(0,1); return first.toUpperCase() + this.substring(1); }; – Dhiraj Himani Feb 06 '17 at 07:47
9
/*
 * 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. //\\
Sapphire_Brick
  • 1,560
  • 12
  • 26
8

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();
}
John Culviner
  • 22,235
  • 6
  • 55
  • 51
daronwolff
  • 1,994
  • 21
  • 18
8

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 !@#$%^&*()}{{[];':",.<>/? .

Chango
  • 6,754
  • 1
  • 28
  • 37
Mradul Pandey
  • 2,034
  • 1
  • 14
  • 12
8

Unicode and Locale Aware

Using current language features:

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

console.log(capitalize('foo bar'));
console.log(capitalize('ѷҥӕ'))
console.log(capitalize('❄⭐'));

// Title Case
console.log(
  'Title Case:',
  'foo bar'
    .split(/\s+/)
    .map(capitalize)
    .join(' '),
);

We accept a destructured string as the only parameter [firstLetter, ...rest], assigning the first character to the variable firstLetter and get an array for the rest of the characters (...rest) 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('')

Rúnar Berg
  • 4,229
  • 1
  • 22
  • 38
8

Using an arrow function:

const capitalize = string => string[0].toUpperCase() + string.slice(1)
giovaniZanetti
  • 452
  • 4
  • 7
8

Elegant

const capitalize = ([firstChar, ...rest]) => `${firstChar.toUpperCase()}${rest.join('')}`;
Manuel del Pozo
  • 155
  • 2
  • 3
  • Doesn't look very elegant to me, not very readable. Typical example of overcomplicating something simple. – Thorvald May 31 '21 at 12:36
8

This code will also handle extra spaces at the start & end of the string.

let val = '  this is test ';
val = val.trim();
val = val.charAt(0).toUpperCase() + val.slice(1);
console.log("Value => ", val);
8

You can use regex approach :

str.replace(/(^|\s)\S/g, letter => letter.toUpperCase());
DMDJ
  • 357
  • 1
  • 6
  • 13
7
var capitalizeMe = "string not starting with capital"

Capitalize with substr

var capitalized = capitalizeMe.substr(0, 1).toUpperCase() + capitalizeMe.substr(1);
Asad Fida
  • 216
  • 2
  • 6
6

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.

Hadnazzar
  • 1,517
  • 19
  • 21
6

I would just use a regular expression:

myString = '    the quick green alligator...';
myString.trim().replace(/^\w/, (c) => c.toUpperCase());
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Abdulmoiz Ahmer
  • 1,953
  • 17
  • 39
5

Just install and load Lodash:

import { capitalize } from "lodash";

capitalize('test') // Test
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
DiaMaBo
  • 1,879
  • 1
  • 18
  • 18
5

Simple ES6 syntax with template string

 const capitalize = (str) => {
   return `${str[0].toUpperCase()}${str.slice(1)}`
   // return str[0].toUpperCase() + str.slice(1)   // without template string
 }
 
 console.log(capitalize("this is a test"));
 console.log(capitalize("the Eiffel Tower"));
 console.log(capitalize("/index.html"));

/*
"this is a test" → "This is a test"
"the Eiffel Tower" → "The Eiffel Tower"
"/index.html" → "/index.html"
*/
Sandeep Amarnath
  • 5,463
  • 3
  • 33
  • 43
4

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);
Jackkobec
  • 5,889
  • 34
  • 34
  • Yes it's simple. That's probably why it was already posted multiple times a decade before your answer was. – miken32 Feb 09 '23 at 18:35
4

This code might work good in some cases:

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

console.log(capitalizeFirstLetter('foo')); // Foo
// But if we had like this it won't work well
console.log(capitalizeFirstLetter('fOo')); // FOo

But if you really want to make sure, that there is only the first letter capitalized and the rest is built out of lowercase letters, you could adjust the code like this:

function capitalizeFirstLetter(string) {
  return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
    
console.log(capitalizeFirstLetter('fOo')); // Foo
Maher Aldous
  • 894
  • 1
  • 10
  • 14
3

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mr. X
  • 264
  • 3
  • 6
3

Like it:

function capitalize(string,a) {
    var tempstr = string.toLowerCase();
    if (a == false || a == undefined)
        return tempstr.replace(tempstr[0], tempstr[0].toUpperCase());
    else {
        return tempstr.split(" ").map(function (i) { return i[0].toUpperCase() + i.substring(1) }).join(" ");
    }
}


capitalize('stack overflow yeah!',true)); //Stack Overflow Yeah!

capitalize('stack stack stack stack overflow yeah!'));//Stack overflow yeah!

https://jsfiddle.net/dgmLgv7b/

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ISFO
  • 135
  • 2
  • 9
3

A one-liner:

'string'.replace(/(^[a-z])/,function (p) { return p.toUpperCase(); } )
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
szanata
  • 2,402
  • 17
  • 17
3

Firstly, I just wanted to clear up what capitalize means in this context. "This String Is Capitalized" Reliable source

You can see from the example provided this is not what the OP is looking for. What it should say is "How do I make the first letter of a string uppercase" (Not capitalize string)

function ucfirst (str) {
    return typeof str != "undefined" ? (str += '', str[0].toUpperCase() + str.substr(1)) : '';
}

Explained

typeof str != "undefined" // Is str set
? // true
str += '' // Turns the string variable into a string
str[0].toUpperCase() // Get the first character and make it upper case
+ // Add
str.substr(1) // String starting from the index 1 (starts at 0)
: // false
''; // Returns an empty string

This will work with any argument or no argument at all.

undefined         === ""
""                === ""
"my string"       === "My string"
null              === "Null"
undefined         === "";
false             === "False"
0                 === "0"
true              === "True"
[]                === ""
[true,0,"",false] === "True,0,,false"
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
TarranJones
  • 4,084
  • 2
  • 38
  • 55
3

function capitalizeEachWord(str) {
    return str.replace(/\w\S*/g, function(txt) {
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    });
}

document.write(capitalizeEachWord('foo BAR God bAD'));
Eduardo Cuomo
  • 17,828
  • 6
  • 117
  • 94
3

A small improvement - every word in titlecase.

String.prototype.toTitleCase = function(){
    return this.replace(/\b(\w+)/g, function(m,p){ return p[0].toUpperCase() + p.substr(1).toLowerCase() });
}

var s = 'heLLo, wOrLD!';
console.log(s.toTitleCase()); // Hello, World!
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Timur Usmanov
  • 83
  • 1
  • 3
  • Please edit with more information. Code-only and "try this" answers are discouraged, because they contain no searchable content, and don't explain why someone should "try this". – abarisone Aug 30 '16 at 09:22
  • A small improvement - doing exactly what the question asked me not to do ‎ – miken32 Feb 09 '23 at 18:32
3

One liner ("inputString can be set to any string"):

inputString.replace(/.{1}/, inputString.charAt(0).toUpperCase())
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Aditya Joshi
  • 245
  • 4
  • 12
  • 1
    [charAt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/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](https://stackoverflow.com/a/33704783/1336653). – noahnu Jan 30 '18 at 19:52
  • 1
    @noahnu there was typo and there are many way to solve the same thing – Aditya Joshi Jan 30 '18 at 22: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. – noahnu Jan 30 '18 at 22:27
  • @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 . – Aditya Joshi Jan 31 '18 at 23:24
3

This one is simple

const upper = lower.replace(/^\w/, c => c.toUpperCase());
victorhazbun
  • 786
  • 8
  • 16
3

1. We'll be using CSS to achieve this. It can also be set from an external CSS.

<span text-transform="capitalize ">The first letter of each word becomes an upper case</span>

2. Using vanilla JavaScript, we could do:

let string = "test case"

string = string[0].toUpperCase() + string.substring(1)
//return "Test case"

Explanation</b/>:

string[0].toUpperCase(): converts the first letter in the string to upper case

string.substring(1): deletes the first letter in the string and returns the remaining characters

text-transform="capitalize": make the first letter of each word in this tag upper case. If you use 'uppercase' as the value of text-transform, every letter in the tag will be a capital letter

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Chukwuemeka Maduekwe
  • 6,687
  • 5
  • 44
  • 67
3

Any type of string can convert --

YoUrStRiNg → Yourstring

var str = yOuRsTrING.toLowerCase(); // Output: yourstring
str.charAt(0).toUpperCase() + str.slice(1); // Output: Y + ourstring = Yourstring
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Omkesh Sajjanwar
  • 575
  • 8
  • 13
3

You can do str.replace(str[0], str[0].toUpperCase())

Check this example:

let str = "hello WORLD"
let newStr = str.replace(str[0], str[0].toUpperCase())

console.log("str: ", str)
console.log("newStr: ", newStr)
Dory Daniel
  • 798
  • 14
  • 21
2

Okay, so I am new to JavaScript. I wasn't able to get the above to work for me. So I started putting it together myself. Here's my idea (about the same, different and working syntax):

String name = request.getParameter("name");
name = name.toUpperCase().charAt(0) + name.substring(1);
out.println(name);

Here I get the variable from a form (it also works manually):

String name = "i am a Smartypants...";
name = name.toUpperCase().charAt(0) + name.substring(1);
out.println(name);

Output: "I am a Smartypants...";

GAMITG
  • 3,810
  • 7
  • 32
  • 51
Alex
  • 77
  • 1
  • 1
2

The function takes two arguments:

start - the start index;
length - the length of substring to capitalise

String.prototype.subUpper = function () {
    var result = this.toString();
    var start = 0;
    var length = 1;
    if (arguments.length > 0) {
        start = arguments[0];
        if (start < this.length) {
            if (arguments.length > 1) {
                length = arguments[1];
            }
            if (start + length > this.length) {
                length = this.length - start;
            }
            var startRest = start + length;
            var prefix = start > 0 ? this.substr(0, start) : String.empty;
            var sub = this.substr(start, length);
            var suffix = this.substr(startRest, this.length - startRest);
            result = prefix + sub.toUpperCase() + suffix;
        }
    }
    return result;
};
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Berezh
  • 942
  • 9
  • 12
2

I have been trying to do same (that is; capitalize the first letter in a string while it is being typed) using jQuery. I searched all through the web for the answer but couldn't find it. However I was able to get a work around using the on() function in jQuery like so:

$("#FirstNameField").on("keydown",function(e){
    var str = $("#FirstNameField").val();
    if(str.substring()===str.substring(0,1)){
        $("#FirstNameField").val(str.substring(0,1).toUpperCase());
    } 
});

This function actually capitalizes the first letter while the data entrant is typing continuously.

falsarella
  • 12,217
  • 9
  • 69
  • 115
user28864
  • 3,375
  • 1
  • 25
  • 19
2

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
  • 30,738
  • 21
  • 105
  • 131
pizzamonster
  • 1,141
  • 10
  • 9
  • What do you mean by *"The currently voted answer"*? Do you mean *"The currently highest voted answer"*? – Peter Mortensen Jun 13 '19 at 23:14
  • @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. – pizzamonster Jun 14 '19 at 22:43
2

This does the same action:

var newStr = string.slice(0,1).toUpperCase() + string.slice(1);
Irfan Syed
  • 113
  • 2
  • 10
  • Won't this result in "the Eiffel Tower" being turned into "The eiffel tower"? The original question involved _not_ changing the case of the other letters. – Andrew Myers Mar 28 '16 at 20:12
  • Yes @AndrewMyers i made the edit which wouldn't change the case of the other letters – Irfan Syed Mar 30 '16 at 15:10
2

If there's Lodash in your project, use upperFirst.

medik
  • 1,174
  • 12
  • 17
2

Capitalize First Word: Shortest

text.replace(/(^.)/, m => m.toUpperCase())

Capitalize Each Word: Shortest

text.replace(/(^\w|\s\w)/g, m => m.toUpperCase());

If you want to make sure the rest is in lowercase:

text.replace(/(^\w|\s\w)(\S*)/g, (_,m1,m2) => m1.toUpperCase()+m2.toLowerCase())
chickens
  • 19,976
  • 6
  • 58
  • 55
  • 1
    This is a much more correct implementation vs other ones. For example if you want: `evence coppéeplaats` to `Evence Coppéeplaats`, your method works correctly, while others will have issues with the `é`. – JoniVR Aug 25 '22 at 09:52
2

Capitalizing the first letter with validation

function capitalizeFirstLetter(str) {
    return (str && typeof str === 'string') ? (str.charAt(0).toUpperCase() + str.slice(1)) : "";
}

Testing

console.log(capitalizeFirstLetter(0)); // Output: ""
console.log(capitalizeFirstLetter(null)); // Output: ""
console.log(capitalizeFirstLetter("test")); // Output: "Test"
console.log(capitalizeFirstLetter({})); // Output: ""
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Satheez
  • 570
  • 7
  • 14
2

I know this is an old question with a lot of answers but here's my quick snippet.

const capitalize = (str) => str?.split('').map( (e, i) => i === 0 ? e.toUpperCase() : e ).join('')
2

Solution for Cannot read property 'charAt' of undefined

const capitalize = (string) => {
        return string ? string.charAt(0).toUpperCase() + string.slice(1) : "";
    }

console.log(capitalize("i am a programmer")); // I am a programmer
1

This is what I use religiously:

function capitalizeMe(str, force){
    str = force ? str.toLowerCase() : str;
    return str.replace(/(\b)([a-zA-Z])/g,
        function(firstLetter){
            return firstLetter.toUpperCase();
        });
}


var firstName = capitalizeMe($firstName.val());
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
kaleazy
  • 5,922
  • 2
  • 47
  • 51
  • 4
    This looks gross in my opinion - in fact I think adding a flag to any method to get it to perform different behavior is a bit daft. Consider `var s = capitalizeMe('some RANDOM string', true);` - a reader of your code isn't going to know what the `true` means without reading the function implementation. If you want your function to do something else, write it in another function instead of overloading the method with magic flags or parameters. – nevelis Oct 23 '14 at 04:50
1
function cap(input) {
    return input.replace(/[\.\r\n\t\:\;\?\!]\W*(\w)/g, function(match, capture) {
         // For other sentences in the text
         return match.toUpperCase();
    }).replace(/^\W*\w/, function(match, capture) {
        // For the first sentence in the text
        return match.toUpperCase();
    });;
}

var a = "hi, dear user. it is a simple test. see you later!\r\nbye";
console.log(cap(a));
// Output: Hi, dear user. It is a simple test. See you later!
// Bye
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
SalmanAA
  • 552
  • 1
  • 6
  • 13
  • The question was: *"How do I make the first letter of a string uppercase in JavaScript?"* This seems to be capitalise *every sentence*. – Peter Mortensen Jan 06 '21 at 22:46
1

Another way using RamdaJs, the functional programming way:

firstCapital(str){
    const fn = p => R.toUpper(R.head(p)) + R.tail(p);
    return fn(str);
}

With multiple words in a string:

firstCapitalAllWords(str){
    const fn = p => R.toUpper(R.head(p)) + R.tail(p);
    return R.map(fn,R.split(' ', str)).join(' ');
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Abhishek Maurya
  • 1,803
  • 1
  • 15
  • 12
1

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("");
};
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
puiu
  • 726
  • 9
  • 18
1

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
  );
};
  • 2
    Could you add details about what the above code does? That would be really useful, and would increase the quality of your answer. – Tyson Phalp Jul 18 '19 at 17:14
1

EDIT : I like this one :

yourString.replace(/(^[a-z])/i, (str, firstLetter) => firstLetter.toUpperCase())
user1075296
  • 581
  • 3
  • 10
1

To capitalize all words:

Typescript version:

const capitalize = (str:string)=>{
        // Split into words
        const words = str.split(" ");
        const resWords:string[] = [];
        // loop over words, slicing and capitalizing the first letter of each word.
        words.forEach(word => {
            const letterOne = word.slice(0, 1);
            const upperCaseLetterOne = letterOne.toUpperCase();
            const otherLetters = word.slice(1);
            const newWord = upperCaseLetterOne+otherLetters
            resWords.push(newWord)
        });
        // Turn it back into a human-readable string.
        return resWords.join(" ");
    }

Javascript version:

const capitalize = (str)=>{
        // Split into words
        const words = str.split(" ");
        const resWords = [];
        // loop over words, slicing and capitalizing the first letter of each word.
        words.forEach(word => {
            const letterOne = word.slice(0, 1);
            const upperCaseLetterOne = letterOne.toUpperCase();
            const otherLetters = word.slice(1);
            const newWord = upperCaseLetterOne+otherLetters
            resWords.push(newWord)
        });
        // Turn it back into a human-readable string.
        return resWords.join(" ");
    }

You can use it like this:

const bookTitle = "my awesome book";
const displayBookTitle = capitalize(bookTitle);
console.log(displayBookTitle) // My Awesome Book

To capitalize the first word:

Typescript:

const capitalize = (str:string)=>{
    return str.charAt(0).toUpperCase() + str.slice(1)
}

Javascript:

const capitalize = (str)=>{
    return str.charAt(0).toUpperCase()+str.slice(1);
}

You use it like so:

console.log(capitalize("foo bar")) // Foo bar
Fighter178
  • 303
  • 2
  • 9
  • Note, for some languages, this may not work. I wrote it to work in English, so you may have to adapt it for it to work in the language you're targeting. – Fighter178 Mar 14 '23 at 18:08
1

Including this answer because this is a one line answer using spread operator. Not as perfomant as other answers. But still does the job without modifiying the original string.

const [firstLetter, ...rest] = "hello world";
console.log(`${firstLetter.toUpperCase()}${rest.join('')}`);
Jeesmon Joy
  • 196
  • 1
  • 2
  • 16
  • Your solution still needs two expressions. For this to be a true one liner it would have to be something like `console.log(([firstLetter, ...rest] = "hello world", \`${firstLetter.toUpperCase()}${rest.join('')}\`))`. – Asplund Jun 30 '23 at 14:18
1

I don't see any other answers mentioning Intl.Segmenter, which "enables locale-sensitive text segmentation" -- meaning you can reliably identify the first character when dealing with characters composed from multiple code points. The big caveat with relying on it in browsers is the lack of Firefox support, see https://caniuse.com/mdn-javascript_builtins_intl_segmenter_segment & https://bugzilla.mozilla.org/show_bug.cgi?id=1423593.

See How can I get a character array from a string? for more details.

There are many excellent answers here already, so I'm solely going to focus on splitting by character.

Using the following test string, which is composed of 9 characters / 15 code points / 20 code units:

const str = '-‍‍-நி-깍-葛';

Naive, split

str.split('');
// (20) ["\ud83d", '\udc05', '-', '\ud83d', '\udc68', '‍', '\ud83d', '\udc69', '‍', '\ud83d', '\udc67', '-', 'ந', 'ி', '-', '깍', '-', '葛', '\udb40', '\udd00']

Slightly better, spread operator

[...str]
// (15) ["", '-', '', '‍', '', '‍', '', '-', 'ந', 'ி', '-', '깍', '-', '葛', '']

Intl.Segmenter (in supported browsers)

[...new Intl.Segmenter().segment(str)].map((g) => g.segment);
// (9) ["", '-', '‍‍', '-', 'நி', '-', '깍', '-', '葛']

graphemer 1.4.0

import Graphemer from 'graphemer';
const splitter = new Graphemer();
splitter.splitGraphemes(str);
// (9) ["", '-', '‍‍', '-', 'நி', '-', '깍', '-', '葛']

lodash 4.17.10

import _ from 'lodash';
_.split(str, '');
// (11) ["", '-', '‍‍', '-', 'ந', 'ி', '-', '깍', '-', '葛', '']

fabric.js v6.0.0-beta10 graphemeSplit (internal function)

import { graphemeSplit } from './fabric_graphemeSplit';
graphemeSplit(str);
// (15) ["", '-', '', '‍', '', '‍', '', '-', 'ந', 'ி', '-', '깍', '-', '葛', '']

@formatjs Intl.Segmenter 11.4.2 polyfill

await import('@formatjs/intl-segmenter/polyfill-force');
[...new Intl.Segmenter().segment(str)].map((g) => g.segment);
// (9) ["", '-', '‍‍', '-', 'நி', '-', '깍', '-', '葛']

Editable comparison: https://stackblitz.com/edit/stackblitz-typescript-lrag9u?devToolsHeight=90&file=index.ts

mrienstra
  • 508
  • 5
  • 7
0

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

Shivam Gupta
  • 149
  • 5
0

I prefer to use a solution oriented to a functional programming (mapping an array):

Array.from(str).map((letter, i) => i === 0 ? letter.toUpperCase() : letter ).join('');
alejoko
  • 993
  • 8
  • 14
0

If you need to have all words starting with a capital letter, you can use the following function:

const capitalLetters = (s) => {
    return s.trim().split(" ").map(i => i[0].toUpperCase() + i.substr(1)).reduce((ac, i) => `${ac} ${i}`);
}

Example:

console.log(`result: ${capitalLetters("this is a test")}`)
// Result: "This Is A Test"
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ruslan Korkin
  • 3,973
  • 1
  • 27
  • 23
0

You should do like that:

let text = "lower case";
text = text.charAt(0).toUpperCase() + text.substring(1, text.length);
Shalabh Negi
  • 621
  • 7
  • 18
Teymur
  • 92
  • 5
0

// capitalize only first character of multi words
var cfc = (str,fs=' ',es=' ')=>{ //str = string, fs = first separator, es = end separator
    var str = str.split(fs);
    var str2=[];
    str.find((item)=>{
        const a = item.charAt(0).toUpperCase()+item.slice(1).toLowerCase();
        str2.push(a);
    });
    return str2.join(es);
}
const str = "stRing1#sTRIng2#strING3";
console.log(cfc(str,'#','@')); // output: String1@String2@String3
console.log(cfc(str,'#',' ')); // output: String1 String2 String3
ramin
  • 448
  • 4
  • 15
-1

In the loop :

function capitalizeFirstIterative(array) {
    let res = [];
    for (let index = 0; index < array.length; index++) {
        const element = array[index];
        res.push(element.charAt(0).toUpperCase() + element.slice(1));
    }
    return res;
}

Recursively :

function capitalizeFirst (array) {
  if (array.length === 1) {
    return [array[0][0].toUpperCase() + array[0].substr(1)];
  }
  const res = capitalizeFirst(array.slice(0, -1));
  const string = array.slice(array.length - 1)[0][0].toUpperCase() + array.slice(array.length-1)[0].substr(1);
  res.push(string);
  return res;
}
-1

try this one line fix

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

function getCapitalizedText(text) {
  return text[0].toUpperCase() + text.substring(1)
}

we can call this "getCapitalizedText" any number of times by passing the text.

Venkatesh Somu
  • 4,710
  • 4
  • 23
  • 22