5302

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"
3
  • 21
    Underscore has a plugin called underscore.string that includes this and a bunch of other great tools.
    – Aaron
    Commented Apr 15, 2013 at 19:16
  • 5
    For those using angular, there is a titlecase pipe: angular.io/api/common/TitleCasePipe
    – ecstrema
    Commented Jan 27, 2021 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. Commented Jun 16, 2021 at 23:17

106 Answers 106

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)

3
  • 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: forwebonly.com/… Commented Feb 13, 2013 at 13:17
  • 1
    Regexp is overkill for this, prefer the simpler : str.charAt(0).toUpperCase() + str.slice(1)
    – Simon
    Commented Jan 23, 2017 at 13:36
  • 1
    Often times, if you want to solve your problem with regex, you end up with two problems.
    – Przemek
    Commented Sep 23, 2017 at 19:18
19

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)}`;
0
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.

3
  • 2
    nice name for the function! It's name is identical to the PHP equivalent. There is actually an entire library of PHP functions written in JS; it's called PHP.js and to be found on http://phpjs.org
    – Hussam
    Commented Dec 8, 2011 at 14:29
  • 12
    One liner: string[0].toUpperCase() + string.substring(1)
    – dr.dimitru
    Commented Nov 25, 2015 at 4:01
  • 2
    What is "aclaration"? Commented Jan 6, 2021 at 23:34
18

You can do it in one line like this

string[0].toUpperCase() + string.substring(1)
1
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"
15

A functional approach

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

Then you could

const titleCase = str => 
  str
    .split(' ')
    .map(capitalize)
    .join(' ')
1
  • 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. Commented Sep 4, 2018 at 11:19
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"
5
  • 12
    This is a JavaScript question.
    – Cobby
    Commented May 6, 2014 at 0:54
  • 15
    @Cobby - And this is a coffeescript answer.
    – longda
    Commented May 6, 2014 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
    Commented Jul 16, 2014 at 17:17
  • 2
    Coffeescript is a preprocessor language, not a library... A library for this would be silly
    – TaylorMac
    Commented Jul 30, 2014 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: coffeescript.org
    – longda
    Commented Jul 30, 2014 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);
2
  • I would go str = str.charAt(0).toLocaleUpperCase() + str.substr(1);, though, to make this shorter
    – YakovL
    Commented Dec 28, 2017 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? Commented Jan 6, 2021 at 23:23
12

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

3
  • first char of word to upper case = word[0].toUpperCase() skipe first char and lower rest = slice(1).toLowerCase(); Commented Jul 19, 2020 at 1: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
    Commented Aug 22, 2020 at 20:28
  • you can ignore the other extra step of code : +word.slice(1).toLowerCase(); Commented Aug 23, 2020 at 0:17
12

CoffeeScript

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

As a String prototype method:

String::capitalize = -> @charAt(0).toUpperCase() + @slice(1)
1
  • 2
    Stupid question but how would you add this to the String prototype in coffeescript?
    – longda
    Commented Aug 15, 2012 at 17:54
11
function capitalize(string) {
    return string.replace(/^./, Function.call.bind("".toUpperCase));
}
2
  • this capitalizes the whole string
    – henhen
    Commented Jun 25, 2018 at 19:09
  • 2
    @henhen no, the regex character ^ asserts position at start. then . matches a single character Commented Jun 28, 2018 at 16:51
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())
11

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 =
        lc ? ( m, p1, p2 ) => p1.toUpperCase() + p2.toLowerCase()
           : ( m, p1, p2 ) => p1.toUpperCase() + p2;
    if( all ) {
        return str.split( /(\s|-|')/ )
                  .map( s => s.replace( /^([A-Za-zÀ-ÖØ-öø-ÿ])(.*)$/, replacer ) )
                  .join( "" )
    } else {
        return str.replace( /^([A-Za-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"
1
  • 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! Commented Apr 4, 2014 at 6:51
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)" />
1
  • 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
    Commented May 17, 2013 at 2:29
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.

1
  • `String.prototype.capitalize = String.prototype.capitalize || function() { var first = this.substring(0,1); return first.toUpperCase() + this.substring(1); }; Commented Feb 6, 2017 at 7:47
9

Or you could use Sugar.js capitalize()

Example:

'hello'.capitalize()           -> 'Hello'
'hello kitty'.capitalize()     -> 'Hello kitty'
'hello kitty'.capitalize(true) -> 'Hello Kitty'
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

9

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

3
  • 1
    can you explain your function capitalize. Commented Nov 20, 2019 at 10:34
  • Why destructuring works with Unicode but string[0] doesn't?
    – Camilo
    Commented Mar 18 at 19:02
  • 1
    @Camilo string[0] works in UTF-16 which has at most 2 bytes (16 bits) per string item, while many unicode characters have 4 bytes (32 bits). Destructuring is ‘unicode’ aware, meaning, it understands which codepoints are 4 bytes and which are 1 or 2 bytes, string[0] isn’t, so it will take at most 2 bytes at a time, which sometimes is only half the character. Commented Mar 29 at 1:25
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. //\\
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"));

0
9

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
s[0].toUpperCase``+s.substr`1`

let s = 'hello there'

console.log( s[0].toUpperCase``+s.substr`1` )

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

8

Using an arrow function:

const capitalize = string => string[0].toUpperCase() + string.slice(1)
8

Elegant

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

You can use regex approach :

str.replace(/(^|\s)\S/g, letter => letter.toUpperCase());
8

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.

7
var capitalizeMe = "string not starting with capital"

Capitalize with substr

var capitalized = capitalizeMe.substr(0, 1).toUpperCase() + capitalizeMe.substr(1);
7

I would just use a regular expression:

myString = '    the quick green alligator...';
myString.trim().replace(/^\w/, (c) => c.toUpperCase());

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