Reputation: 54397
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"
Upvotes: 5371
Views: 4447067
Reputation: 17138
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 String(s[0]).toUpperCase() + String(s).slice(1);
}
According to the comments below this doesn't work in IE 7 or below.
To avoid undefined
for empty strings (see @njzk2's comment below), you can check for an empty string:
function capitalize(s)
{
return s && String(s[0]).toUpperCase() + String(s).slice(1);
}
const capitalize = s => s && String(s[0]).toUpperCase() + String(s).slice(1)
// to always return type string event when s may be falsy other than empty-string
const capitalize = s => (s && String(s[0]).toUpperCase() + String(s).slice(1)) || ""
Upvotes: 514
Reputation: 125640
function capitalizeFirstLetter(val) {
return String(val).charAt(0).toUpperCase() + String(val).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).
Upvotes: 8114
Reputation: 7443
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!)
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 (Unicode scalar value) 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 firstCodePoint = str.codePointAt(0);
const index = firstCodePoint > 0xFFFF ? 2 : 1;
return String.fromCodePoint(firstCodePoint).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("𐐶𐐲𐑌𐐼𐐲𐑉") // "𐐎𐐲𐑌𐐼𐐲𐑉"
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 \p{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).
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.
Upvotes: 312
Reputation: 585
function capitalize(word) {
return word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase();
}
You create a function that takes a word string as input. You use the Substring class to give you the first character of the string. You then use the toUpperCase()
to capitalize that character.
You then concatenate the rest of the string to that with the string minus the first character to which you apply the toLowerCase()
method.
Typically you would use two values to the subString
class. The place where you want the splicing of the string to start and where you want it to end, but if you provide only one value to the subString
class in will splice from that value to the end of the string (Like what we have in the second case.) and remember the subString
class is zero indexed.
Upvotes: 7
Reputation: 63
You can achieve this in JavaScript by splitting the string into an array of words, capitalizing the first letter of the first word, and then joining the words back into a string. Here's how you can do it:
function capitalizeFirstLetter(str) {
str = str.charAt(0).toUpperCase() + str.slice(1);
// Join the words back into a string
return str;
}
// Example usage:
console.log(capitalizeFirstLetter("this is a test")); // Output: "This is a test"
console.log(capitalizeFirstLetter("the Eiffel Tower")); // Output: "The Eiffel Tower"
console.log(capitalizeFirstLetter("/index.html")); // Output: "/index.html"
This function capitalizeFirstLetter
takes a string as input
, splits it into an array of words using the space character as a delimiter, capitalizes the first letter of the first word, and then joins the words back into a string with spaces.
Upvotes: 3
Reputation: 12345
Using just CSS and its text-transform
property:
p::first-letter {
text-transform: capitalize;
}
Upvotes: 1172
Reputation: 317
charAt and toUpperCase: You can use the charAt method to get the first character of the string and then use toUpperCase to convert it to uppercase. After that, you can concatenate the rest of the string.
function capitalizeFirstLetter(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
let inputString = "hello world";
let result = capitalizeFirstLetter(inputString);
console.log(result); // Output: Hello world
charAt and slice: Another way is to use slice to get the substring from the second character to the end of the string and then concatenate it with the uppercase first character.
function capitalizeFirstLetter(str) {
return str.slice(0, 1).toUpperCase() + str.slice(1);
}
let inputString = "hello world";
let result = capitalizeFirstLetter(inputString);
console.log(result); // Output: Hello world
Upvotes: 1
Reputation: 1112
Note Important Information UTF-8 uses variable length encoding that means it supports up to 4 bytes for a single char the codePointAt(1) >> 7 indicates thats prv codePoint is a Char also codePointAt() >> 7 if codePointAt(1) >> 11 it indicates we got a 2 bytes utf 8 message so 16 and 21 are the indicators for 4 bytes utf-8 chars. So codePointAt(4) >> 21 === 0 indicates its a 4 byte utf-8 char. All this checks are costly so the most performant efficient method on all string length is
const upperCaseFirstLatterUtf8 = (str) => {
const b = str.substr(0,4).normalize();
return b[0].toUpperCase() + b.substr(1) + str.substr(4);
}
upperCaseFirstLatterUtf8('\u006E\u0303me!')
That's the only correct method to handle utf-8 chars as explained they got variable length of up to 4 bit this uses normalize which is relative expensive but the only performant way to archive our goal even checking all the charCodes is not faster. Then we return the remaining chars and the uppercase first letter as single utf-32 char so it is always 4 bit and shifts by 7
Upvotes: 1
Reputation: 3320
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:
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"
Upvotes: 11
Reputation: 622
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 = '🐅-👨👩👧-நி-깍-葛󠄀';
str.split('');
// (20) ["\ud83d", '\udc05', '-', '\ud83d', '\udc68', '', '\ud83d', '\udc69', '', '\ud83d', '\udc67', '-', 'ந', 'ி', '-', '깍', '-', '葛', '\udb40', '\udd00']
[...str]
// (15) ["🐅", '-', '👨', '', '👩', '', '👧', '-', 'ந', 'ி', '-', '깍', '-', '葛', '󠄀']
[...new Intl.Segmenter().segment(str)].map((g) => g.segment);
// (9) ["🐅", '-', '👨👩👧', '-', 'நி', '-', '깍', '-', '葛󠄀']
import Graphemer from 'graphemer';
const splitter = new Graphemer();
splitter.splitGraphemes(str);
// (9) ["🐅", '-', '👨👩👧', '-', 'நி', '-', '깍', '-', '葛󠄀']
import _ from 'lodash';
_.split(str, '');
// (11) ["🐅", '-', '👨👩👧', '-', 'ந', 'ி', '-', '깍', '-', '葛', '󠄀']
import { graphemeSplit } from './fabric_graphemeSplit';
graphemeSplit(str);
// (15) ["🐅", '-', '👨', '', '👩', '', '👧', '-', 'ந', 'ி', '-', '깍', '-', '葛', '󠄀']
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
Upvotes: 4
Reputation: 480
// 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
Upvotes: 0
Reputation: 5020
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.
Upvotes: 9
Reputation: 246
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('')}`);
Upvotes: 3
Reputation: 826
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)
Upvotes: 2
Reputation: 5341
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.
Upvotes: 34
Reputation: 1207
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).
Upvotes: 51
Reputation: 3975
If the transformation is needed only for displaying on a web page:
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
).const capitalizeFirstChar = str => str.charAt(0).toUpperCase() + str.substring(1);
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)
.substring()
and slice()
The difference is rather minuscule nowadays (run the test yourself):
substring()
,slice()
.Upvotes: 70
Reputation: 104870
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'
Upvotes: 63
Reputation: 118
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;
}
Upvotes: -1
Reputation: 413
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
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
Upvotes: 2
Reputation: 17703
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!"
Upvotes: 1641
Reputation: 1120
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('');
Upvotes: 0
Reputation: 2115
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)
Upvotes: 21
Reputation: 4452
s[0].toUpperCase``+s.substr`1`
let s = 'hello there'
console.log( s[0].toUpperCase``+s.substr`1` )
Upvotes: 9
Reputation: 3770
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>
Upvotes: 21
Reputation: 6936
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"
*/
Upvotes: 4
Reputation: 120
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
Upvotes: 2
Reputation: 597
EDIT : I like this one :
yourString.replace(/(^[a-z])/i, (str, firstLetter) => firstLetter.toUpperCase())
Upvotes: 1
Reputation: 942
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
Upvotes: 3
Reputation: 1715
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"]
Upvotes: 21