In this article we will learn how to capitalize first letter of word.
It is very common to capitalize first letter of word in JavaScript.
Problem
Now we have a problem, which is that we want to make the first letter of each word a capital.
Now we have a word like that
let string = "hello in my world";
And we want to make the first letter of each word a capital like that:
"Hello In My World"
How to solve this problem?
Is there a built-ind function that does this? The answer is no!
But you have to do this yourself, but of course in the presence of other functions it will be easy.
Explain the solution
Well, what will be the solution?
First we have to make the word into an array, then iterate over that array and capitalize the first letter of each element in the array (a word), and then return the array to a string again.
The solution will be as follows:
- Use the
split()
method to split the string into an array. - Iterate over elements using
map
- Use the
slice()
andcharAt()
methods to capitalize each element of the array. - Then return the array to a string again using
join
method
Solution
First we have to split the string into an array.
// String
let string = 'hello in my world'
// Split into an array
const split = string.split(' ');
// Result:
console.log(split);
Output
[ 'hello', 'in', 'my', 'world' ]
Then we have to iterate over elements and capitalize first letter of each word.
// String
const string = 'hello in my world'
// Split into an array
const split = string.split(' ');
// Capitalize each element:
const capitalize = split.map(word => {
return word.charAt(0).toUpperCase() + word.slice(1)
});
console.log(capitalize);
Output
[ 'Hello', 'In', 'My', 'World' ]
Then return the array to a string again using join
method
// String
const string = 'hello in my world'
// Split into an array
const split = string.split(' ');
// Capitalize each element:
const capitalize = split.map(word => {
return word.charAt(0).toUpperCase() + word.slice(1)
});
// Back to string
const toString = capitalize.join(' ');
// Result:
console.log(toString);
Output
Hello In My World
Thank you for reading
Thank you for reading my blog. 🚀