Capitalize the first letter of any string in JavaScript

Written by
Published on
Modified on

While there is no direct bulit-in function in JavaScript (yet) to capitalize the first letter of a string, there are various ways that you can implement this yourself.

Using charAt and slice

Using a combination of charAt() and slice() can yield the desired results. The charAt() method returns the character at a specified index in a string, starting at zero.

let word = 'hello';
let firstchar = word.charAt(0);  // returns 'h'

And the slice() method returns a shallow copy of a portion of an array into a new array. The method takes 2 arguments, the starting index and the ending index that you want to slice out.

You can also simply specify a single argument, the starting index, in which case the slice() method will return everything from the starting location to the end of the array.

let words = ['word1', 'word2', 'word3'];

// returns ['word2', 'word3']
let slice1 = words.slice(1);

Using these two methods we can combine them to get the desired results, first by calling charAt(0) on the desired string in order to get the first character and then using the built in toUpperCase() method to capitalize it. And secondly by calling the slice() method to include everything except for the first character and  concatenating these results together.

let word = 'hello';
let capitalize = word.charAt(0).toUpperCase() + word.slice(1)

This is pretty useful if you are working on any type of code used for text editing. While you could use CSS to capitalize the first letter of an array, note that this isn't really a true capitalization. The rendering engine will simply show the capital letter, but the content won't be changed in any way.

Until the JavaScript standard introduces a native way to do this, this is the simplest approach that I have found and used so far.

Leave a comment

No messages posted yet

Add a comment

Send me your weekly newsletter filled with awesome ideas
Post