EN
JavaScript - first letter of each word uppercase
0 points
In this article, we would like to show you how to make the first letter of each word uppercase in JavaScript.
Quick solution:
xxxxxxxxxx
1
var text = 'this is example text...';
2
3
const array = text.split(' ');
4
5
for (let x = 0; x < array.length; ++x) {
6
array[x] = array[x].charAt(0).toUpperCase() + array[x].slice(1);
7
}
8
var result = array.join(' ');
9
10
console.log(result);
In this example, we make the first letter of each word uppercase using:
split()
method split the text into an array of separate words,charAt()
method withtoUpperCase()
to uppercase the first letter of each word,slice()
method to get the rest of the word - without the first letter, so we can add it to the uppercase letter.join()
method to convert the array back to the string.
xxxxxxxxxx
1
function uppercase(text) {
2
var array = text.split(' ');
3
4
for (var x = 0; x < array.length; ++x) {
5
array[x] = array[x].charAt(0).toUpperCase() + array[x].slice(1);
6
}
7
return array.join(' ');
8
}
9
10
11
// Usage example:
12
13
console.log(uppercase('this is example text...'));
Output:
xxxxxxxxxx
1
This Is Example Text...
In this section, we present a solution that is equal to the above one but written in modern syntax.
xxxxxxxxxx
1
const uppercase = (text) => {
2
const array = text.split(' ');
3
4
for (let x = 0; x < array.length; ++x) {
5
array[x] = array[x].charAt(0).toUpperCase() + array[x].slice(1);
6
}
7
return array.join(' ');
8
};
9
10
11
// Usage example:
12
13
console.log(uppercase('this is example text...'));
Output:
xxxxxxxxxx
1
This Is Example Text...