In JavaScript there are many ways to capitalize the first letter of a string. I will show some of them here and when to use each one.


Using charAt() toUpperCase() and slice()

The first way and probably the easiest way would be to use 2 functions. First, using the build in function charAt(0) we can get the first character of the string and then by using toUpperCase() we can make this character uppercase. Then using the + operator we concatenate the result of the previous functions to the word.slice(1) function which will return the string after the first character. Also here I decided to use ES6 syntax.

const capitalizeFirstLetter = (word) => word.charAt(0).toUpperCase() + word.slice(1);

capitalizeFirstLetter('pico Coder'); //'Pico Coder'
capitalizeFirstLetter('pico'); //'Pico'
capitalizeFirstLetter('PICO'); //'PICO'
capitalizeFirstLetter(''); //''
capitalizeFirstLetter(1); // TypeError: word.charAt is not a function

If you would like this in previous versions of JavaScript you can write it like this

function capitalizeFirstLetter(word) { 
   return word.charAt(0).toUpperCase() + word.slice(1);
}

capitalizeFirstLetter('pico Coder'); //'Pico Coder'
capitalizeFirstLetter('pico'); //'Pico'
capitalizeFirstLetter('PICO'); //'PICO'
capitalizeFirstLetter(''); //''
capitalizeFirstLetter(1); // TypeError: word.charAt is not a function

Using the object oriented way

We can add an additional property on the string prototype which is basically this function.

String.prototype.capitalizeFirstLetter = function capitalizeFirstLetter() { 
   return this.charAt(0).toUpperCase() + this.slice(1);
}

const word = 'pico Coder'.capitalizeFirstLetter(); //'Pico Coder'

Pro Tip: Do not use arrow functions here since the keyword this does not reference the object therefore this will not work.


Using only CSS

The aforementioned ways will work in both frontend and backend. However, if you only want to capitalize the first letter of a string in the frontend and more specifically in the presentation layer of your website then you can use only css to do it.

p.capitalize {
  text-transform: capitalize;
}

Capitalize First Letter


If you liked the tutorial, please consider subscribing to my blog. That way I get to know that my work is valuable to you and also notify you for future tutorials. Stay tuned!