In JavaScript, and programming in general, one can solve the same problem in various ways. When it comes to first letter capitalization, JavaScript offers a few ways to implement it in the console output.
Method toUpperCase() and slice()
This function is applied to a string and changes all letters of it to uppercase. You might stipulate that you only need a single letter to remain capitalized. This function is still suitable for such purposes. It is achieved by combining this function with other JavaScript functionality. As of now, the syntax of the toUpperCase()
function looks like this:
string.toUpperCase()
The return of this function is a capitalized string. You should also be aware that this function works better when used in aggregate with the slice()
function. More precisely, it applies to a string, allowing one to slice it according to the passed parameters. The syntax of this function is as follows:
string.slice(start, end)
Please note that start
and end
parameters are essential to specify where the slicing position begins and finishes. In other words, start
signals the beginning of slicing, and its indexing starts from 0. As for the end
parameter, it specifies the exact position from where to stop slicing. Although it's an optional value, it selects all characters from the start
parameter if you ignore it.
So, how does the combination of these two functions allow capitalizing the first letter? Check the following example:
function capitalize(str) {
return `${str.charAt(0).toUpperCase()}${str.slice(1)}`;
}
console.log(capitalize('test')); // Output: Test
Still, combining the toUpperCase()
and slice()
seems to be the most straightforward and accessible capitalization approach in JavaScript.
Function charAt()
You can also combine three different functions to capitalize the first letter in JavaScript. As a whole, charAt()
function is used to return the character to a determined position in a string. Try working with the following code:
const str = 'example';
const str2 = str.charAt(0);
console.log(str2); // Output: e
In this example, the return you see in a console is "e
." But what if you mix this function with replace()
and experiment with a console for a while? Try combining the following examples in your compiler:
const str = "example";
const firstChar = str.charAt(0);
const capitalized = str.replace(firstChar, firstChar.toUpperCase());
console.log(capitalized); // Output: "Example"
// Alternative one-line solution with regex
const capitalized2 = str.replace(/^(.)/, (match) => match.toUpperCase());
console.log(capitalized2); // Output: "Example"
In the first case, we use the word example
and get the output of Example
as a return. The same goes for example
, which capitalizes only E
in this input. It works because the charAt()
function returns the character at a given position, while toUpperCase()
converts all the characters of an input string into upper cases.
But why do we get only the first letter capitalized? If we provide a substring instead of a regex pattern as the first argument, only the first occurrence will be replaced. In the second example, we use a regular expression pattern and match the first character, and then we transform it using the callback function.
Capitalizing the first letter in each word
What if you need to capitalize the first letter of each word in your sentence? In this case, you'll need to split the words from their respective strings and store them in an array.
Your next step is to use the mentioned combination of functions to each array and join all the array elements back. As a result, you'll get a string back and get the expected return in your console. Consider this as an example:
const str = 'learning javascript is actually fun and not that complicated';
const arr = str.split(' ');
for (let i = 0; i < arr.length; i++) {
arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].slice(1);
}
const str2 = arr.join(' ');
console.log(str2);
In this prompt, we entered the following sentence: "learning javascript is actually fun and not that complicated". Not only do we really think so, but we can also explain how the use of an array works in this situation.
Firstly, you split the sentence string into an array of strings, only to loop through each element to capitalize the first letter. Secondly, you join all the array elements back into a string, using a blank space as a separator between them. Voila, your return will look like this:
Learning Javascript Is Actually Fun And Not That Complicated
Method map()
Because JavaScript has a comprehensive functionality, you can also capitalize the first letter using the map
method. Check out how it works before we elaborate on its nuances:
function capitalize(...words) {
return words.map((word) => `${word.slice(0, 1).toUpperCase()}${word.slice(1)}`).join(' ');
}
console.log(capitalize('some', 'kind', 'of', 'lower-cased', 'words', '...'));
// Output: Some Kind Of Lower-cased Words ...
With this method, you include the function capitalize(),
and use the …
(rest operator) and toUpperCase()
function. There you use the map()
method, which creates a new array from provided arguments, after remapping, you should use join
to unite the separate words into one string
.
Alternatives
The examples mentioned above are the more accessible methods to capitalize letters. You can also experiment using other methods, which are best known as using RegEx
or rest
. Since they are more complicated and less readable, they are rarely used for upper cases.
Instead, most developers rely on combining charAt()
, toUpperCase()
and slice()
, replace()
functions since they offer the most variability.