Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make the first letter of a string uppercase in JavaScript?

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"
like image 850
Robert Wills Avatar asked Jun 22 '09 08:06

Robert Wills


People also ask

How do you capitalize the first letter in a string JavaScript?

To capitalize the first character of a string, We can use the charAt() to separate the first character and then use the toUpperCase() function to capitalize it.

How do you capitalize a string in JavaScript?

To capitalize an entire string, simply call . toUpperCase() on the string: let myString = 'alligator'; myString.

How do you capitalize first letter?

To use a keyboard shortcut to change between lowercase, UPPERCASE, and Capitalize Each Word, select the text and press SHIFT + F3 until the case you want is applied.


1 Answers

The basic solution is:

function capitalizeFirstLetter(string) {   return string.charAt(0).toUpperCase() + string.slice(1); }  console.log(capitalizeFirstLetter('foo')); // Foo

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).

...and then, there is so much more to this question when you consider internationalisation, as this astonishingly good answer (buried below) shows.

If you want to work with Unicode code points instead of code units (for example to handle Unicode characters outside of the Basic Multilingual Plane) you can leverage the fact that String#[@iterator] works with code points, and you can use toLocaleUpperCase to get locale-correct uppercasing:

const capitalizeFirstLetter = ([ first, ...rest ], locale = navigator.language) =>   first.toLocaleUpperCase(locale) + rest.join('')  console.log(   capitalizeFirstLetter('foo'), // Foo   capitalizeFirstLetter("πΆπ²π‘ŒπΌπ²π‘‰"), // "πŽπ²π‘ŒπΌπ²π‘‰" (correct!)   capitalizeFirstLetter("italya", 'tr') // Δ°talya" (correct in Turkish Latin!) )

For even more internationalization options, please see the original answer below.

like image 166
Steve Harrison Avatar answered Oct 06 '22 07:10

Steve Harrison