JavaScript: Convert a string to title case

JavaScript String: Exercise-34 with Solution

Write a JavaScript function to convert a string to title case.

Test Data:
console.log(sentenceCase('PHP exercises. python exercises.'));
"Php Exercises. Python Exercises."

Visual Presentation:

JavaScript: Convert a string to title case

Sample Solution:

JavaScript Code:

// Define a function named sentenceCase that takes a string str as input
function sentenceCase (str) {
  // Check if the input string is null or empty
  if ((str===null) || (str===''))
       return false;
   // Convert the input string to a string type
   str = str.toString();

 // Replace each word in the string with its first letter capitalized and the rest in lowercase
 return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});

// Call the sentenceCase function with a test string and log the result to the console
console.log(sentenceCase('PHP exercises. python exercises.'));


Php Exercises. Python Exercises.


In the exercise above,

  • The function "sentenceCase()" checks if the input string is null or empty. If so, it returns 'false'.
  • If the input string is not null or empty, it is converted to a string type.
  • The "replace()" method is used with a regular expression '\w\S*' to match each word in the string.
  • For each match found, a callback function is invoked. Inside this function, the first character of the word is capitalized using "charAt(0).toUpperCase()", and the rest of the word is converted to lowercase using "substr(1).toLowerCase()".
  • The modified words are then concatenated to form the final sentence.
  • The function returns the modified sentence.


Flowchart: JavaScript- Convert a string to title case

Live Demo:

See the Pen JavaScript Convert a string to title case-string-ex-34 by w3resource (@w3resource) on CodePen.

Improve this sample solution and post your code through Disqus.

Previous: Write a JavaScript function to remove non-word characters.
Next: Write a JavaScript function to remove HTML/XML tags from string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Follow us on Facebook and Twitter for latest update.