Algorithm Title Case A Sentence - ashish9342/FreeCodeCamp GitHub Wiki

Algorithm Title Case a Sentence

🚩 Remember to use Read-Search-Ask if you get stuck. Try to pair program 👥 and write your own code 📝

🏁 Problem Explanation:

We have to return a sentence with title case. This means that the first letter will always be in uppercase and the rest will be in lowercase.

Relevant Links

💬 Hint: 1

  • You should start by splitting the string into an array of words.
  • Split the sentence.

try to solve the problem now

💬 Hint: 2

  • You should make the word lowercase before making the first letter uppercase.
  • Use replace method on each word to capitalize the first letter of each word.

try to solve the problem now

💬 Hint: 3

  • You will need to create a new string with pieces of the previous one and at the end merge everything into a single string again.
  • In replace method, give first argument as the position of the first letter using charAt. For second argument write a function to return the capitalized letter as the replacement.

try to solve the problem now

Spoiler Alert!

687474703a2f2f7777772e796f75726472756d2e636f6d2f796f75726472756d2f696d616765732f323030372f31302f31302f7265645f7761726e696e675f7369676e5f322e676966.gif

Solution ahead!

🔰 Basic Code Solution:

String.prototype.replaceAt = function(index, character) {
    return this.substr(0, index) + character + this.substr(index+character.length);
};


function titleCase(str) {
    var newTitle = str.split(' ');
    var updatedTitle = [];
    for (var st in newTitle) {
        updatedTitle[st] = newTitle[st].toLowerCase().replaceAt(0, newTitle[st].charAt(0).toUpperCase());
    }
    return updatedTitle.join(' ');
}

🚀 Run Code

Code Explanation:

We are modifying the replaceAt function using prototype to facilitate the use of the program.

Split the string by white spaces, and create a variable to track the updated title. Then we use a loop to turn turn the first character of the word to uppercase and the rest to lowercase. by creating concatenated string composed of the whole word in lowercase with the first character replaced by it's uppercase.

Relevant Links

🌻 Intermediate Code Solution:

function titleCase(str) {
  var convertToArray = str.toLowerCase().split(" ");
  var result = convertToArray.map(function(val){
      return val.replace(val.charAt(0), val.charAt(0).toUpperCase());
  });
  return result.join(" ");
}

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

🚀 Run Code

Code Explanation:

We are making entire string lowercase and then converting it into array. Then we are using map function to replace the lowercase character with uppercase. Finally, we are returning the string using join method.

Relevant Links

🚨 Advanced Code Solution:

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

🚀 Run Code

Code Explanation:

The solution works by first lowercasing all the characters in the string and then only uppercasing the first character of each word.

  • Lowercase the whole string using str.toLowerCase().

  • Replace every word' first character to uppercase using .replace.

  • Search for words and a lowercase character at the beginning of each word i.e. matching any lowercase character following a space or matching the first character of the whole string, by using the following pattern.

  • Regex explanation:

    • ( |^) matches a space character or beginning of the whole string (^).
    • [a-z] matches a single character in the range between a to z (case sensitive i.e. lowercase).
  • The g modifier searches for other such word pattern in the whole string and replaces them.

Relevant Links

🏆 Credits:

If you found this page useful, you can give thanks by copying and pasting this on the main chat:

Thanks @Rafase282 @PoojaKumar @Hallaathrad @abhisekp @ksharifbd for your help with Algorithm: Title Case a Sentence

📋 NOTES FOR CONTRIBUTIONS:

  • ⚠️ DO NOT add solutions that are similar to any existing solutions. If you think it is similar but better, then try to merge (or replace) the existing similar solution.
  • Add an explanation of your solution.
  • Categorize the solution in one of the following categories — Basic, Intermediate and Advanced. 🚥
  • Please add your username only if you have added any relevant main contents. (:warning: DO NOT remove any existing usernames)

See 👉 Wiki Challenge Solution Template for reference.

⚠️ **GitHub.com Fallback** ⚠️