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"
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"
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).
the Eiffel Tower -> The Eiffel Tower
. Plus, the function is called capitaliseFirstLetter
not capitaliseFirstLetterAndLowerCaseAllTheOthers
.
– ban-geoengineering
Aug 2 '14 at 10:24
A more object-oriented approach:
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
And then:
"hello world".capitalize(); => "Hello world"
return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
– ma11hew28
Mar 8 '11 at 18:21
In CSS:
p:first-letter {
text-transform:capitalize;
}
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);
}
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);
}
.slice(1)
with .substr(1)
would enhance performance even further.
– Przemek
Sep 23 '17 at 19:37
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();
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(" ");
}
string.replace(string[0], string[0].toUpperCase());
to be a lot easier
– Gcap
Mar 20 '17 at 17:46
::first-letter
as this variant is in line with CSS3 philosophy when it comes to those colons, 2) use .substring(…)
rather than .slice(…)
as it has better performance, 3) OP didn't wanted to lowercase all other characters, 4) Don't modify prototype of objects you don't own
– Przemek
Oct 11 '17 at 16:50
var string = "hello world";
string = string.charAt(0).toUpperCase() + string.slice(1);
alert(string);
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(" ");
}
s => s.split(' ').map(x => x[0].toUpperCase() + x.slice(1)).join(' ')
– OverCoder
Jul 28 '17 at 18:10
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
.slice()
is slower than .substring()
, str[0]
would be undefined
for an empty string and using template literals to join the two parts introduces in here 8 characters, while +
would introduce only 3.
– Przemek
Jun 4 '18 at 8:40
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);
}
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();
});
};
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"
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
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"
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 7 '15 at 14:11
p::first-letter {
text-transform: uppercase;
}
::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.:first-letter
).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);
parameters => function
is so called arrow function.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.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)
.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
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).
It's always better to handle these kinds of stuff using CSS first, in general, if you can solve something using CSS, go for that first, then try JavaScript to solve your problems, so in this case try using :first-letter
in CSS and apply text-transform:capitalize;
So try creating a class for that, so you can use it globally, for example: .first-letter-uppercase
and add something like below in your CSS:
.first-letter-uppercase:first-letter {
text-transform:capitalize;
}
Also the alternative option is JavaScript, so the best gonna be something like this:
function capitalizeTxt(txt) {
return txt.charAt(0).toUpperCase() + txt.slice(1); //or if you want lowercase the rest txt.slice(1).toLowerCase();
}
and call it like:
capitalizeTxt('this is a test'); // return 'This is a test'
capitalizeTxt('the Eiffel Tower'); // return 'The Eiffel Tower'
capitalizeTxt('/index.html'); // return '/index.html'
capitalizeTxt('alireza'); // return 'Alireza'
If you want to reuse it over and over, it's better attach it to javascript native String, so something like below:
String.prototype.capitalizeTxt = String.prototype.capitalizeTxt || function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
and call it as below:
'this is a test'.capitalizeTxt(); // return 'This is a test'
'the Eiffel Tower'.capitalizeTxt(); // return 'The Eiffel Tower'
'/index.html'.capitalizeTxt(); // return '/index.html'
'alireza'.capitalizeTxt(); // return 'Alireza'
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'
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
return.this.toLocaleLowerCase().replace(
...
– tomdemuyt
Jan 14 '13 at 21:55
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
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.
substr()
is deprecated? It's not, even now, three years later, let alone back in 2009 when you made this comment.
– Dan Dascalescu
Nov 7 '12 at 6: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
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
var str = "test string";
str = str.substring(0,1).toUpperCase() + str.substring(1);
Checkout this solution:
var stringVal = 'master';
stringVal.replace(/^./, stringVal[0].toUpperCase()); // returns Master
stringVal.replace(/^./, stringVal[0].toUpperCase());
– Alfredo Delgado
Oct 15 '15 at 19:30
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
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.)
There is a very simple way to implement it by replace. For ES6:
'foo'.replace(/^./, str => str.toUpperCase())
result:
'Foo'
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[0] || '').toUpperCase() + string.substring(1)
– dr.dimitru
May 6 '16 at 18:20
You can do it in one line like this
string[0].toUpperCase() + string.substring(1)
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.
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"
String.prototype.capitalize = function () { return this.substring(0,1).toUpperCase() + this.substring(1).toLowerrCase() }
– Shiala
Jul 16 '14 at 17:17
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
Jul 30 '14 at 23:28
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
string[0].toUpperCase() + string.substring(1)
– dr.dimitru Nov 25 '15 at 4:00