如何在 JavaScript 中使用字符串大写字母的第一个字母?

How do I make the first letter of a string uppercase, but not change the case of any of the other letters?

For example:

  • "this is a test" -> "This is a test"
  • "the Eiffel Tower" -> "The Eiffel Tower"
  • "/index.html" -> "/index.html"

转载于:https://stackoverflow.com/questions/1026069/how-do-i-make-the-first-letter-of-a-string-uppercase-in-javascript

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

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.

A more object-oriented approach:

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

And then:

"hello world".capitalize();  =>  "Hello world" 

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.

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

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

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

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

It seems to be easier in 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).

In CSS:

p:first-letter {
    text-transform:capitalize;
}

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"
yourString.replace(/^[a-z]/, function(m){ return m.toUpperCase() });

(You may encapsulate it in a function or even add it to the String prototype if you use it frequently.)

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();
  });
};
var string = "hello world";
string = string.charAt(0).toUpperCase() + string.slice(1);
alert(string);

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();
String.prototype.capitalize = function(allWords) {
   return (allWords) ? // if all words
      this.split(' ').map(word => word.capitalize()).join(' ') : //break down phrase to words then  recursive calls until capitalizing all words
      this.charAt(0).toUpperCase() + this.slice(1); // if allWords is undefined , capitalize only the first word , mean the first char 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 Nov.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 char which is capitalized by `toUpperCase()` method
 ).join('')                                             //return back to string

then capitalize("hello") // Hello

var str = "test string";
str = str.substring(0,1).toUpperCase() + str.substring(1);

If you use underscore.js or Lo-Dash, 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"
var str = "ruby java";

alert(str.charAt(0).toUpperCase() + str.substring(1));

it will return "Ruby java"

http://jsfiddle.net/amitpandya/908c8e2v/

result link in jsfiddle

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'

Checkout this solution:

var stringVal = 'master';
stringVal.replace(/^./, stringVal[0].toUpperCase()); // returns Master 

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

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

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

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

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

See their docs: 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 js for first upper case:

function upperCaseFirst(str){
    return str.charAt(0).toUpperCase() + str.substring(1);
}
var capitalized = yourstring[0].toUpperCase() + yourstring.substr(1);

Here are the best solutions:

First Solution In CSS:

p {
  text-transform: capitalize;
}

Second solution :

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

You could also add it to the String.prototype so you could chain it with other methods:

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

and use it like this:

'string'.capitalizeFirstLetter() // String

Third Solution:

function ucFirstAllWords( str )
{
    var pieces = str.split(" ");
    for ( var i = 0; i < pieces.length; i++ )
    {
        var j = pieces[i].charAt(0).toUpperCase();
        pieces[i] = j + pieces[i].substr(1).toLowerCase();
    }
    return pieces.join(" ");
}

CSS only

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

Since there are numerous answers, but none in ES2015 that would solve original problem efficiently, I came up with the following:

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

Remarks

  • parameters => function is so called arrow function.
  • I went with name capitalizeFirstChar instead of capitalizeFirstLetter, because OP didn't asked for code that capitalizes the first letter in the entire string, but the very first char (if it's letter, of course).
  • const gives us the ability to declare capitalizeFirstChar as constant, which is desired since as a programmer you should always explicitly state your intentions.
  • 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 empty string, so it should be rewritten to string && string[0], which is way too verbose, compared to the alternative.
  • string.substring(1) is faster than string.slice(1).

Benchmark

  • 4,956,962 ops/s ±3.03% for this solution,
  • 4,577,946 ops/s ±1.2% for the most voted answer.
  • Created with JSBench.me on Google Chrome 57.

Solutions' comparison

It's always better handle these kinds of stuffs 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 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'

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'

You can do it in one line like this

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

This is the 2018 ES6+ Solution:

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

</div>
yourString.replace(/\w/, c => c.toUpperCase())

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