w3resource

JavaScript: Capitalize each word in the string

JavaScript String: Exercise-41 with Solution

Write a JavaScript function to capitalize each word in the string.

Test Data:
console.log(capitalizeWords('js string exercises'));
"JS STRING EXERCISES"

Visual Presentation:

JavaScript: Capitalize each word in the string

Sample Solution:

JavaScript Code:

// Define a function called capitalizeWords that takes a string str as input
function capitalizeWords(str) {
    // Use the replace method with a regular expression \w\S* to match each word in the string
    // For each matched word, execute a callback function
    return str.replace(/\w\S*/g, function(txt) {
        // Inside the callback function, convert the first character of the word to uppercase
        // and keep the rest of the word unchanged
        return txt.substr(0).toUpperCase();
    });
}
// Call the capitalizeWords function with the input string 'js string exercises' and print the result to the console
console.log(capitalizeWords('js string exercises'));

Output:

JS STRING EXERCISES

Explanation:

In the exercise above,

  • function capitalizeWords(str) {: Defines the function "capitalizeWords()" with a parameter 'str', representing the input string.
  • return str.replace(/\w\S*/g, function(txt) {: Uses the "replace()" method with a regular expression '\w\S*' to match each word in the string. For each matched word, it executes a callback function.
  • return txt.substr(0).toUpperCase(); });: In the callback function, it converts the first character of each word to uppercase using the "toUpperCase()" method and keeps the rest of the word unchanged.
  • console.log(capitalizeWords('js string exercises'));: Calls the "capitalizeWords()" function with the input string 'js string exercises' and prints the capitalized string to the console.

Flowchart:

Flowchart: JavaScript: capitalize the each word of a string

Live Demo:

See the Pen JavaScript Capitalize each word in the string-string-ex-41 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus.

Previous: Write a JavaScript function to Uncapitalize the first letter of each word of a string.
Next: Write a JavaScript function to uncapitalize each word in the string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/javascript-exercises/javascript-string-exercise-41.php