Capitalize first letter of a string | JavaScript

There are number of ways to to capitalize a string to make the first character uppercase.

inString[0].toUpperCase() + inString.slice(1);

In the above code, uppercases the first character and slices the string to returns it starting from the second character.


example
const inString = 'javascript'; const outString = inString[0].toUpperCase() + inString.slice(1); console.log(outString);
Output:
Javascript

capitalize the first character

Using string.charAt()

const inString = 'javascript'; const outString = inString.charAt(0).toUpperCase() + inString.slice(1); console.log(outString);
Output:
Javascript

Using string.replace()

const inString = 'javascript'; const outString = inString.replace(/^./, inString[0].toUpperCase()); console.log(outString);
Output:
Javascript

Capitalize the first letter of each word

You can easily convert the first letter of each word of a string into uppercase by splitting the sentence into words using the split() method and applying charAt(0).toUpperCase() on each word.

const inString = 'capitalize the first letter of each word in javaScript'; const inArr = inString.split(" "); for (var count = 0; count < inArr.length; count++) { inArr[count] = inArr[count].charAt(0).toUpperCase() + inArr[count].slice(1); } const outString = inArr.join(" "); console.log(outString);
Output:
How to Capitalize the First Letter of Each Word in JavaScript

JavaScript charAt()

JavaScript charAt() method returns the character at a specified index (position) in a string. The index of the first character is 0, the second 1, third 2 etc. The index of the last character is string length - 1

JavaScript toUpperCase()

JavaScript toUpperCase() method converts a string object into a new string consisting of the contents of the first string, with all alphabetic characters converted to be upper-case.

JavaScript slice()

The JavaScript array slice() method extracts the part of the given array and returns it.

Make first letter of a string uppercase in CSS

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 :first-letter in CSS and apply text-transform:capitalize;

p::first-letter { text-transform:capitalize; }

Conclusion

These methods provide different ways to capitalize the first letter of a string in JavaScript, catering to various preferences and coding styles. Choose the method that best suits your needs and coding context.