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\"
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);
}
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
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).
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);
}
var capitalized = yourstring[0].toUpperCase() + yourstring.substr(1);
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.)