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:
// ONLINE-RUNNER:browser;
var text = 'this is example text...';
const array = text.split(' ');
for (let x = 0; x < array.length; ++x) {
array[x] = array[x].charAt(0).toUpperCase() + array[x].slice(1);
}
var result = array.join(' ');
console.log(result);
Practical example
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.
// ONLINE-RUNNER:browser;
function uppercase(text) {
var array = text.split(' ');
for (var x = 0; x < array.length; ++x) {
array[x] = array[x].charAt(0).toUpperCase() + array[x].slice(1);
}
return array.join(' ');
}
// Usage example:
console.log(uppercase('this is example text...'));
Output:
This Is Example Text...
Modern syntax - reusable arrow function
In this section, we present a solution that is equal to the above one but written in modern syntax.
// ONLINE-RUNNER:browser;
const uppercase = (text) => {
const array = text.split(' ');
for (let x = 0; x < array.length; ++x) {
array[x] = array[x].charAt(0).toUpperCase() + array[x].slice(1);
}
return array.join(' ');
};
// Usage example:
console.log(uppercase('this is example text...'));
Output:
This Is Example Text...