1

I'm new to JavaScript and am having a bit of trouble with this problem:

Construct 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.

5
  • 2
    Because you are comparing an array against a string, and those are 2 completely different things. Btw, if the array is empty, just let the join work. It will return an empty string. Do not make an special if for it. I mean, just remove the if (text === "") { return "" } Commented Nov 11, 2021 at 18:17
  • 1
    FWIW, edge cases like this can be tested from the JS console, e.g., what does ””.split() return? What are the effects of calling join on that result? Experimenting in the console provides a quick way to test assumptions (and code) without having to run a complete program/function/etc. Commented Nov 11, 2021 at 18:19
  • 1
    This doesn't have to be a JS task. CSS can deal with it. Commented Nov 11, 2021 at 18:25
  • Just move your if (text === "") to the first line before text = text.split(' '); Commented Nov 11, 2021 at 18:25
  • @Andy If it’s on a web page, sure ;) But I’m not bringing in a virtual browser and selectors for my back-end app :D Commented Nov 11, 2021 at 18:41

5 Answers 5

1

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"

Sign up to request clarification or add additional context in comments.

Comments

1

You just have to declare text empty as default in the function and add the if (text === "") { condition before the for loop. So if the text is empty then before executing the for loop it will return "". Please check the following snippet:

const titleCase = function(text = '') {
    if (text === "") {
       return ""
     }
  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('');
  }

  return text.join(' ');
}

console.log(titleCase());
console.log(titleCase("Hello"));
console.log(titleCase("Hello World"));

Comments

0

You can just use this simple function to solve this problem.

function titleCase(text) {
    return text.split(' ').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ')
}

Now let's break it down a little bit.

First I'm using text.split(' '). It converts the sentence into an array of each word.

For example,

"this is an example" became ['this', 'is', 'an', 'example']

Second, I'm using map() to convert each word to be capitalized.

word.charAt(0).toUpperCase() + word.slice(1). This is a simple way to convert a word to be capitalized. It became:

['this', 'is', 'an', 'example']``` to ```['This', 'Is', 'An', 'Example']

And finally I'm just joining each word with a space:

join(' ')

Then it returns "This Is An Example".

2 Comments

Does this work for an empty string? (The question says "It is passing all tests except for the empty string "" test.")
sure, you can test it
0

You can’t modify a character with the [] notation.

To replace the first character of a string, don't do

str[0] = str[0].toUppercase()

but

str = "X" + str.substr(1)

Your function can be:

function titleCase(str) {
  return str.toLowerCase().replace(/(^|\s)[a-z]/g, (a)=>a.toUpperCase());
}

This function will:

  • convert all to lower case
  • then use a regular expression to replace letters ([a-z]) following a space (\s) or the beginning of the string (^) with its uppercase version.

2 Comments

Does this work for an empty string? (The question says "It is passing all tests except for the empty string "" test.")
@PeterMortensen yes, titleCase("") return an empty string
-1

These console.log lines (after text = text.split(' ');) should help you understand your mistake:

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

  console.log(text)
  console.log(text.length)

  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(' ');
}

2 Comments

Instead of posting ways to debug the existing code as questions provide detailed answers that will actually provide an answer to the question.
It is fine to include debugging tips, but an answer should actually answer the question, not merely be hints (unless it is a blatant homework dump). Please improve your answer. (But without "Edit:", "Update:", or similar - the answer should appear as if it was written today.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.