Making the first letter of a string uppercased in JavaScript

January 04, 2020 No comments JS Uppercase String JavaScript

1. Introduction

In this article, we will present several methods to uppercase first letter of a string in JavaScript.

2. Dedicated function

Uppercasing the first character of a string is simple, we need to get that very first letter, uppercase it and connect with the rest of a string.

The following function doing exactly that:

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

Example of use:

console.log(capitalizeFirstLetter("this is example text")); // This is example text
console.log(capitalizeFirstLetter("/test")); // /test
console.log(capitalizeFirstLetter("john")); // John

3. Modify String.prototype

Modifying the String.prototype gives us the ability to call a function that will uppercase first character directly on String objects.

The following JavaScript code extending prototype methods of a String with new function capitalize that will be available on every String object in the running application:

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

Example of use:

console.log("this is example text".capitalize()); // This is example text
console.log("john".capitalize()); // John

4. Using CSS style

The other way to uppercase first character is to use CSS style if the only result we want to achieve is printing uppercased Strings on the website.

p:first-letter {
    text-transform:capitalize;
}

5. Conclusion

In this article, we presented methods to uppercase a first character in JavaScript. For this purpose, we can use a dedicated function, modify the prototype of a String object or use CSS style. It is up to you what function you will use, however when after choosing String.prototype modification, keep in mind that this could cause conflicts if other code that uses the same name, or browsers adds a native function with the same name to String objects in future.

{{ message }}

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