How can I capitalize the first letter of a string using Angular or typescript?
- Check this [reference links][blog]. There will be solution. [blog]: stackoverflow.com/questions/30207272/…Michał Dębosz– Michał Dębosz2018-03-15 10:07:44 +00:00Commented Mar 15, 2018 at 10:07
- 7This is not a duplicate. Pipes are the correct angular way to do thisLiam– Liam2019-04-30 11:19:45 +00:00Commented Apr 30, 2019 at 11:19
- 1This is not a duplicate. This is an Angular question, not a javascript one. A custom pipe should be used, which does not exist in regular javascript.Kurt Van den Branden– Kurt Van den Branden2023-03-13 06:21:57 +00:00Commented Mar 13, 2023 at 6:21
Add a comment |
3 Answers
function titleCaseWord(word: string) { if (!word) return word; return word[0].toUpperCase() + word.substr(1).toLowerCase(); } You can also use in template TitleCasePipe
Some component template:
{{value |titlecase}} 9 Comments
Alex Peters
Note that the
TitleCasePipe will capitalise the first letter of every word in the string, not just the first letter of the entire string—so the TitleCasePipe is not strictly an option for what has been asked.Paul A. Trzyna
This should not be the accepted answer. Like Alex mentioned, TitleCasePipe will capitalize very word. Answers below should be accepted. Alternative is a custom pipe.
Matias de Andrea
⚠️ Be carful with this solution, because in some languages (like Spanish) when you have a question string, start with character
¿Esto es una pregunta?. So, when apply this algorithm in spanish questions, don't work properly. I add this: if (value[0] === '¡' || value[0] === '¿') { return ( value[0] + value[1].toUpperCase() + value.substr(2).toLowerCase() ); }Michael Murphy
@MatiasdeAndrea I wonder if
toLocaleUpperCase() would help hereMatias de Andrea
Is a nice question @MichaelMurphy. I don't test this
|
var str = 'santosh'; str = str ? str.charAt(0).toUpperCase() + str.substr(1).toLowerCase() : ''; 2 Comments
Toby Speight
Thank you for this code snippet, which might provide some limited short-term help. A proper explanation would greatly improve its long-term value by showing why this is a good solution to the problem, and would make it more useful to future readers with other, similar questions. Please edit your answer to add some explanation, including the assumptions you've made, such as languages with which it doesn't work correctly.
Santosh Singh
Yes Sure, Thanks for your advice