w3resource

JavaScript: Uncapitalize the first letter of each word of a string

JavaScript String: Exercise-40 with Solution

Write a JavaScript function to uncapitalize the first letter of each word of a string.

Test Data:
console.log(unCapitalize_Words('Js String Exercises'));
"js string exercises"

Visual Presentation:

JavaScript: Uncapitalize the first letter of each word of a string

Sample Solution:

JavaScript Code:

// Define a function named unCapitalize_Words which takes a string str as input
function unCapitalize_Words(str)
{ 
  // Use the replace method with a regular expression /\w\S*/g to match words in the string
  // For each word matched, execute the callback function(txt) where txt is the matched word
  return str.replace(/\w\S*/g, 
    // Inside the callback function, convert the first character of the word to lowercase
    // and concatenate it with the rest of the word converted to lowercase
    function(txt)
       {
          return txt.charAt(0).toLowerCase() + txt.substr(1).toLowerCase();
       });
}

// Call the unCapitalize_Words function with the input string 'Js String Exercises'
// and print the result to the console
console.log(unCapitalize_Words('Js String Exercises'));

Output:

js string exercises

Explanation:

In the exercise above,

  • The "unCapitalize_Words()" function takes a string 'str' as input.
  • It uses the "replace()" method with a regular expression '\w\S*' to match each word in the string.
  • For each matched word, a callback function is executed, where 'txt' represents the matched word.
  • Inside the callback function, it converts the first character of the word to lowercase using 'charAt(0).toLowerCase()', and then concatenates it with the rest of the word converted to lowercase using 'substr(1).toLowerCase()'.
  • The function returns the modified string with all words having their first character in lowercase.
  • Finally, the function is called with the input string 'Js String Exercises', and the result is printed to the console.

Flowchart:

Flowchart: JavaScript: Uncapitalize  the first character of a string

Live Demo:

See the Pen JavaScript Uncapitalize the first letter of each word of a string-string-ex-40 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus.

Previous: Write a JavaScript function to uncapitalize  the first character of a string.
Next: Write a JavaScript function to capitalize 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://w3resource.com/javascript-exercises/javascript-string-exercise-40.php