How to capitalize the first letter of a string in JavaScript

Published Sep 10 2022

To capitalize the first letter of a string in JavaScript, we can combine the .toUpperCase() method with the .slice() method:

far out logo

Code Playground

Loading...

The .toUpperCase() function returns a copy of the string upon which it is invoked with all alphabetic characters in upper case (capitalized). The .slice(startIndex, startIndex) method returns a section of a string beginning and ending at the indices which are passed to it as arguments. If the endIndex argument is ommitted, .slice() extracts the substring all the way to the end of the original string

Capitalize the first letter of each word in a string

Consider the case where we have a string which contains multiple words, and we want to capitalize the first letter of each word. Here, the .split() method may be used to split the string into an array of words. This array can then be mapped over using the .map() method, and each word can be capitalized using the same method as above. Finally, we can convert out array back into a string using .join(). You can see the steps in action in the Code Playground below:

far out logo

Code Playground

Loading...
This was pretty far out... now tell me about Binary Search in JavaScript
Far Out Logo
That was pretty far out... but I want to learn about How to use the React useCallback() hook