In this tutorial you’ll learn how to change the first letter of every word to upper case using JavaScript.
Capitalizing with split
, for
loop and join
If you’re just getting started with JavaScript, then I suggest the most obvious step-by step approach to capitalizing each word in string.
- Split the string into the array of words
- Capitalize each word in the array you got on step 1
- Join the array back into a string
Putting our plan into the code will look like this.
const exampleString = 'I will become a software engineer';
const array = exampleString.split(" ");
for (let i = 0; i < array.length; i++) {
array[i] = array[i].charAt(0).toUpperCase() + array[i].substring(1);
}
const capitalized = array.join(" ");
console.log(capitalized); // I Will Become A Software Engineer
If you’re looking to make your code reusable, you can always wrap it into a function.
const capitalize = (s) => {
const array = exampleString.split(" ");
for (let i = 0; i < array.length; i++) {
array[i] = array[i].charAt(0).toUpperCase() + array[i].substring(1);
}
return array.join(" ");
}
Then, you can call it wherever you like.
const exampleString = 'I will become a software engineer this year!';
console.log(capitalize(exampleString)); // I Will Become A Software Engineer This Year!
Introducing map
You can make the split
, for
and join
approach more concise if you use the function map
instead of the for
loop.
This way you can chain the function calls.
const exampleString = 'Learn hard go pro';
const capitalized = exampleString
.split(" ")
.map(word => word.charAt(0).toUpperCase() + word.substring(1))
.join(" ");
console.log(capitalized); // Learn Hard Go Pro
Capitalize every word using a regular expression
Regular expression most likely look weird and alien to you if you’re just starting to learn JS.
However, it’s a perfectly fine way to capitalize each word in JavaScript string.
Here’s a code sample where I use the regular expression /(^\w{1})|(\s+\w{1})/g
to get the desired outcome.
const exampleString = 'I am starting to learn right now!';
const capitalized = exampleString.replace(/(^\w{1})|(\s+\w{1})/g, letter => letter.toUpperCase());
console.log(capitalized);
Output:
I Am Starting To Learn Right Now!