Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I solve this javascript titlecase problem?

I’m new to javascript and am having a bit of trouble with this problem:
Construct the a function called titleCase that takes a sentence string and gives it title casing.

titleCase("this is an example") //should return "This Is An Example"

titleCase("test") //should return "Test"

titleCase("i r cool") //should return "I R Cool"

titleCase("WHAT HAPPENS HERE") //should return "What Happens Here"

titleCase("") //should return ""

titleCase("A") //should return "A"

This is the code I’ve tried:

const titleCase = function(text) {
  text = text.split(' ');

  for (let i = 0; i < text.length; i++) {
    text[i] = text[i].toLowerCase().split('');
    text[i][0] = text[i][0].toUpperCase();
    text[i] = text[i].join('');
  }
  
  if (text === "") {
       return ""
     } 

  return text.join(' ');
}

It is passing all tests except for the empty string "" test.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You will need to move:

 if (text === "") {
   return ""
 } 

to the first line of the function.

Here is a straightforward solution:

function titleCase(s){
   let r="";
   for (let i=0; i<s.length; i++) r+=(i==0 || s[i-1]==" ")?s[i].toUpperCase():s[i].toLowerCase();
   return r;
}
console.log(titleCase("helLo tHERE!"));
console.log(titleCase("this is an example")); //should return "This Is An Example"
console.log(titleCase("test")); //should return "Test"
console.log(titleCase("i r cool")); //should return "I R Cool"
console.log(titleCase("WHAT HAPPENS HERE")); //should return "What Happens Here"
console.log(titleCase("")); //should return ""
console.log(titleCase("A")); //should return "A"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading