LearnFrenzy
Sign in Take a free test

Strings · Strings Coding Problems · Question 3

Convert a sentence to title case in JavaScript Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

Convert " the quick BROWN fox " to title case (first letter of each word upper case, the rest lower case), collapsing extra spaces.

Solution
main.js
function titleCase(sentence) {
  return sentence
    .trim()
    .split(/\s+/)                                        // one or more spaces
    .map((w) => w[0].toUpperCase() + w.slice(1).toLowerCase())
    .join(" ");
}

console.log(titleCase("  the quick BROWN fox  "));
console.log(titleCase("javaScript is FUN"));

Output Verified by running it on Node.js

The Quick Brown Fox
Javascript Is Fun

trim removes outer spaces, split(/\s+/) treats runs of spaces as one separator, and each word is rebuilt from its first letter and the lower-cased rest.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links