How to Uppercase the First Letter of a String in JavaScript

Unfortunately, there is no utility for capitalising the first letter of a string in JavaScript, only toUpperCase() which converts all chars in a string to uppercase. With that said there are ways around this by splitting the string and using the char index to achieve the desired result.

 

In this guide, we will look at how to uppercase the first letter in a string in JavaScript.

 

Use charAt and slice

If we can get the first letter of a string, capitalise it, and then join it to the original string minus the first letter we would achieve the desired result. Let's create a ucfirst function which we can supply with a string and get a capitalized output.

 

var str = 'hello';

function ucfirst(string) {
  return string.charAt(0).toUpperCase() + string.slice(1);
}

var captalized = ucfirst(str);


console.log(captalized);
Hello

 

What's happening in the ucfirst function is we are getting the character at index 0 of the string using charAt(), then capitalizing it using toUpperCase(). Then we are joining the rest of the string using + (plus) and slicing it at index 1. We are slicing at one because the first character is at index 0.

 

The problem with the above function is if something other than a string is supplied the function will throw an error. It will also throw an error if an empty string is supplied.

 

Let's improve our capitalisation function to validate a string and check for empty strings. We will also replace the charAt() with its shorthand [] (square brackets).

 

var str = 'hello';

function ucfirst(string) {

  if (typeof string === 'string' && string.length > 0) {
    return string[0].toUpperCase() + string.slice(1);
  }

  return;
}

var captalized = ucfirst(str);

console.log(captalized);
Hello

 

The same output is returned, however, if the string cannot be capitalized it will just return undefined.

 

Conclusion

If you are looking to capitalize the beginning of every word in a string, things can get a little more complex. In those cases, I would opt for capitalizing the string server-side or using CSS3's text-transform: capitalize;.

letter uppercase text slice