/

How to Uppercase the First Letter of a String in JavaScript

How to Uppercase the First Letter of a String in JavaScript

Capitalizing the first letter of a string in JavaScript is a common operation that can be achieved using different methods. In this blog, we will explore the various ways you can accomplish this task using plain JavaScript.

To capitalize the first letter of a string, we can combine two functions. The first function, charAt(0), returns the first character of the string. We then use the toUpperCase() function to convert this character to uppercase. Finally, we use the slice(1) function to extract the remaining characters of the string. Here’s an example:

1
2
const name = 'flavio';
const nameCapitalized = name.charAt(0).toUpperCase() + name.slice(1);

To make the code reusable, we can create a function called capitalize(). This function takes a parameter s and checks if it is a string. If the parameter is not a string, the function returns an empty string. Otherwise, it capitalizes the first letter of the string using the same logic as before. Here’s the modified code:

1
2
3
4
5
6
7
8
9
const capitalize = (s) => {
if (typeof s !== 'string') return '';
return s.charAt(0).toUpperCase() + s.slice(1);
}

capitalize('flavio'); // 'Flavio'
capitalize('f'); // 'F'
capitalize(0); // ''
capitalize({}); // ''

Alternatively, instead of using s.charAt(0), we can use string indexing s[0] (not supported in older IE versions).

Although some online solutions suggest adding the capitalize() function to the String prototype, this approach is not recommended. Editing the prototype can cause issues and is slower compared to using an independent function.

If you only need to capitalize the first letter for presentational purposes on a web page, CSS provides a better solution. You can simply add a capitalize class to your HTML paragraph and use the CSS text-transform: capitalize; property. Here’s an example:

1
2
3
p.capitalize {
text-transform: capitalize;
}

In summary, there are multiple ways to capitalize the first letter of a string in JavaScript. By understanding these methods, you can choose the approach that best suits your needs.

tags: [“javascript”, “string manipulation”, “uppercase”, “plain JavaScript”]