How to make the first letter of a string uppercase in JavaScript?

September 29, 2022 No comments uppercase javascript tips solutions js

Introduction

In JavaScript, there are situations when we wish to make the first letter of a string uppercase.

In this article, we'll learn how to uppercase first letter of a string in JavaScript;

How to make the first letter of a string uppercase in JavaScript

To make the first letter of a string uppercase in modern JavaScript we can use the toLocalUpperCase() method:

const capitalizeFirstLetter = ([ first, ...rest ], locale = navigator.language) =>
  first === undefined ? '' : first.toLocaleUpperCase(locale) + rest.join('')

console.log(capitalizeFirstLetter('this is a test')); // This is a test

In older browsers, we can simply take the first letter of a string and call toUpperCase() on it. This first uppercased letter is concatenated with the rest of a string:

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

Conclusion

To make the first letter of a string uppercase in JavaScript we can use the toLocalUpperCase() method with string destructuring. We can also use destructuring to to remove a property from an object.

{{ message }}

{{ 'Comments are closed.' | trans }}