66

How can I capitalize the first letter of a string using Angular or typescript?

3
  • Check this [reference links][blog]. There will be solution. [blog]: stackoverflow.com/questions/30207272/… Commented Mar 15, 2018 at 10:07
  • 7
    This is not a duplicate. Pipes are the correct angular way to do this Commented Apr 30, 2019 at 11:19
  • 1
    This 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. Commented Mar 13, 2023 at 6:21

3 Answers 3

103
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}} 
Sign up to request clarification or add additional context in comments.

9 Comments

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.
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.
⚠️ 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() ); }
@MatiasdeAndrea I wonder if toLocaleUpperCase() would help here
Is a nice question @MichaelMurphy. I don't test this
|
27
let str: string = 'hello'; str = str[0].toUpperCase() + str.slice(1); 

Comments

4
var str = 'santosh'; str = str ? str.charAt(0).toUpperCase() + str.substr(1).toLowerCase() : ''; 

2 Comments

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.
Yes Sure, Thanks for your advice

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.