Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

112
Views
Title Case a Sentence using for loop

I am so close in completing this exercise. The instruction is to convert the str into this new string Here Is My Handle Here Is My Spout.

My code is returning exactly Here Is My Handle Here Is My Spout but when I tried to console.log(result.split(" ")) it was returning with this [ '', 'Here', 'Is', 'My', 'Handle', 'Here', 'Is', 'My', 'Spout' ] .

I am trying to get rid of the empty string in the index 0 but I can't seem to remove it. I am also thinking that I am returning the arrays of the words when I passed it in the result instead of a string?

function titleCase(str) {
  const words = str.toLowerCase().split(" ");
  let result = "";
  for (let word of words) {
let firstCap = word.replace(word[0], word[0].toUpperCase());
 result = result + " " + firstCap;
  }
  console.log(result.split(" "))
  return result;
}

console.log(titleCase("HERE IS MY HANDLE HERE IS MY SPOUT"));
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The problem is with the line:

result = result + " " + firstCap;

When result has value "" you should not add a space but rather an empty string as follows:

result = result + (result.length ? " " : "") + firstCap;

function titleCase(str) {
  const words = str.toLowerCase().split(" ");
  let result = "";
  for (let word of words) {
    let firstCap = word.replace(word[0], word[0].toUpperCase());
    result = result + (result.length ? " " : "") + firstCap;
  }
  console.log(result.split(" "))
  return result;
}

console.log(titleCase("HERE IS MY HANDLE HERE IS MY SPOUT"));

A better approach would be to use Array#map() followed by Array#join().

function titleCase(str) {
  const words = str.toLowerCase().split(" ");
  return words.map(word => word.replace(word[0], word[0].toUpperCase())).join(" ");
}

console.log(titleCase("HERE IS MY HANDLE HERE IS MY SPOUT"));

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!