How to uppercase the First Letter of a String in JavaScript

Last updated on Sep 7, 2020 by Suraj Sharma



In this tutorial, you will learn how you can uppercase the first letter of a string.

Doing it from a CSS file is quite simple, setting a text-transform selector to capitalize does your job.


p {
  text-transform: capitalize
}

Luckily, capitalizing a string in JavaScript can also be done by adding one line of code.



Uppercase First Letter


We are required to get the first character of the string using string.chartAt(0) or simply string[0] and then concatenating the substring starting from index 1 and ending at string.length with the uppercase first character.


Here is a JavaScript function to uppercase the first letter of a string.


function upperCaseFirstLetter (string) {
  return string[0].toUpperCase() + string.slice(1);
}

// ES6 Arrow function

const upperCaseFirstLetter = (string)=>string[0].toUpperCase() + string.slice(1);

console.log(upperCaseFirstLetter('uppercase')) // 'Uppercase'

We have used string.slice() method to get the substring starting from index one.

We can also use string.substring() method to get the substring. You can choose either of them, they don’t have any performance differences between them.

Same way, we can uppercase the first letter of each substring separated with a whitespace in string or a sentence.


Here is a simple JavaScript function to Title Case the string.


function titleCaseString (string) {
  return string.split(' ').map((str)=>upperCaseFirstLetter(str)).join(' ');
}

console.log(titleCaseString('title case string in JavaScript')) // 'Title Case String In JavaScript'

We have split the string with a whitespace, used the above upperCaseFirstLetter() function inside the Array.map() method and finally, joined the newly returned array using Array.join() method, the final result is a title case string.



Related Solutions


Rate this post


Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.