Basic Algorithm Scripting - Title Case a Sentence

Hi! I feel like most of the solutions to this challenge that I’ve seen use concepts that weren’t introduced before this point. I don’t remember .toUpperCase() and .toLowerCase() being introduced, although I could be wrong, and there are other keywords that I’m sure I haven’t seen before. It may be a good idea to introduce these keywords earlier on, before this challenge. However, I believe I’ve found a solution that only incorporates these two new keywords and nothing else, like “.join.”

Is it viable? It does pass all the tests and worked to complete the challenge.

My solution

function titleCase(str) {
  str += " "
  let words = [] 
  let word = ""
  for (let i = 0; i < str.length; i++) { 
    if (str[i] != " ") { 
      if (str[i - 1] == " " || i == 0) {
        word += str[i].toUpperCase();
      } else {
      word += str[i].toLowerCase(); 
      }
    } else if (str[i] == " ") {
      words.push(word); 
      word = ""
    } 
  } 
  console.log(words); 
  let newSentence = ""
  for (let j = 0; j < words.length; j++) {
    newSentence += `${words[j]}` 
    if (j < words.length - 1) {
      newSentence += " "
    }
  } 
  console.log(newSentence) 
  return newSentence
}
  

titleCase("I'm a little tea pot");

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36

Challenge: Basic Algorithm Scripting - Title Case a Sentence

Link to the challenge:

did you try looking into “Get Hint” section?! they usually give out big guns for any of those exercises, but i can see how that can be useful to talk about that beforehand.

but you see, its a test and you are “supposed” to know basic Javascript and its methods to work with, so that being said, its understandable that these exercises are considering that you are aware of those methods and ready to use them

well, thats just my take on this matter, perhaps mods and contributors can help even more :slight_smile:

happy learning :slight_smile:

Hey @houseofraven2,

I actually took some time to check whether there are some exercises for working with String methods prior to this challenge and I failed to see any. You may be right about that. However, there are exercises on Array object and working with its methods like splice, slice, push so you should have some basic understand that these built-in Object can do some things.

If you worked on all exercises prior this one, you should have solid basics of the language. Most often, solving challenges requires additional knowledge and if you think you can’t think of any solution with what you know at the moment, you may need to start looking for some answers online (older posts on this forum, web search), e.g. “How to capitalise character in JS”. It is part of the learning process.

A solution using String.charCodeAt & String.fromCharCode()

// NOTE. This solution is considering only English alphabet

function isUpperCaseLetter(char) {
  return char >= "A" && "Z" >= char;
}

function isLowerCaseLetter(char) {
  return char >= "a" && "z" >= char;
}

function isLetter(char) {
  return isLowerCaseLetter(char) || isUpperCaseLetter(char);
}

function isSpace(char) {
  return char === " ";
}

function toUpperCase(char) {
  if (isLowerCaseLetter(char)) {
    return String.fromCharCode(char.charCodeAt(0) - 32);
  }
  return char;
}

function toLowerCase(char) {
  if (isUpperCaseLetter(char)) {
    return String.fromCharCode(char.charCodeAt(0) + 32);
  }
  return char;
}

function titleCase(str) {
  let titleCase = "";
  let isNewWord = true;
  let index = 0;
  
  // traverse str and check each character
  // if it is a letter and it is new word, capitalize it
  //  if not new word, change it to lower case
  // if it is a space, indicate a new word
  // add the character to the final string
  while (index < str.length) {
    let char = str[index];

    if (isLetter(char)) {
      if (isNewWord) {
        // knowledge of ASCII table and use of
        // built-in String methods charCodeAt() and fromCharCode()
        // lower and upper case letters are 32 points appart
        char = toUpperCase(char);
        isNewWord = false;
      } else {
        // 1. option
        char = toLowerCase(char);
      }
    } else if (isSpace(char)) {
      isNewWord = true;
    }

    titleCase += char;
    index++;
  }

  return titleCase;
}

A solution using String.toUpperCase() without comments

function isUpperCaseLetter(char) {
  return char >= "A" && "Z" >= char;
}

function isLowerCaseLetter(char) {
  return char >= "a" && "z" >= char;
}

function isLetter(char) {
  return isLowerCaseLetter(char) || isUpperCaseLetter(char);
}

function isSpace(char) {
  return char === " ";
}

function titleCase(str) {
  let titleCase = "";
  let isNewWord = true;
  let index = 0;
  
  while (index < str.length) {
    let char = str[index];

    if (isLetter(char)) {
      if (isNewWord) {
        char = char.toUpperCase();
        isNewWord = false;
      } else {
        char = char.toLowerCase();
      }
    } else if (isSpace(char)) {
      isNewWord = true;
    }

    titleCase += char;
    index++;
  }

  return titleCase;
}

As you can see, there’s no need to use Array. Check each character, modify it if necessary and append it to the final sentence. Try to keep it simple.

If you want, you can try to replace isLetter and isSpace with RegEx expressions to exercise this matter even further. And once you finish the “Functional programming” section, you may try this exercise again and make the code only few lines long.

PS. Shorter code !== (Readable && More efficient)

Edit: @DDorf I missed the last line in his post. I was thinking he did not solve the challenge yet. I have put back in your two solutions using the different methods, but have blurred them. We still do not want to give away solutions for those who have not completed the challenge

Sorry for the misunderstanding

Hey,

I find this censorship very unreasonable in this instance as he already solved the challenge. I was showcasing 2 other ways to solve the problem with good coding practice in mind. It is important for learners to see others solutions too - to observe certain patterns. I also addressed him to further improve the code by using other techniques. Moreover, I was trying to demonstrate the existence of ASCII table and how it can be worked with.

???

Yes, I edited the post a few minutes ago as I took his post as he was still seeking help on completing the challenge, and not looking for help of making it better. It will remain blurred though, as it is good for those learning to see how it can be done in different ways but we still want them to figure it out for themselves before giving solutions.

Thanks

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.