freeCodeCamp Algorithm Challenge Guide: Title Case a Sentence

freeCodeCamp Algorithm Challenge Guide: Title Case a Sentence
0.0 0

#1

:triangular_flag_on_post: Remember to use Read-Search-Ask if you get stuck. Try to pair program :busts_in_silhouette: and write your own code :pencil:

:checkered_flag: 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

:speech_balloon: Hint: 1

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

try to solve the problem now

:speech_balloon: 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

:speech_balloon: 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!

:beginner: Basic 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");

:rocket: 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

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

:rocket: 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 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

:rotating_light: Advanced Code Solution:

function titleCase(str) {
  return str.toLowerCase().replace(/(^|\s)\S/g, (L) => L.toUpperCase());
}

:rocket: 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’s first character to uppercase using .replace.

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

  • Regex explanation:

    • Find all non-whitespace characters (\S)
    • At the beginning of string (^)
    • Or after any whitespace character (\s)
  • The g modifier searches for other such word pattern in the whole string and replaces them.

  • This solution works with national symbols and accented letters as illustrated by following examples
    international characters: ‘бабушка курит трубку’ // -> ‘Бабушка Курит Трубку’
    accented characters: ‘località àtilacol’ // -> ‘Località Àtilacol’

Relevant Links

:clipboard: NOTES FOR CONTRIBUTIONS:

  • :warning: 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. :traffic_light:
  • Please add your username only if you have added any relevant main contents. (:warning: DO NOT remove any existing usernames)

See :point_right: Wiki Challenge Solution Template for reference.


What is the advantage of a for loop over map() in the 'Title Case a Sentence' algorithm and Other Questions?
Question from the 'Title Case' challenge. This part ---> String.prototype.replaceAt
#2

#3

#4

I made a different solution without the Arrow function.

function titleCase(str) {
  return str.toLowerCase().replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); });
}
titleCase("I'm a little tea pot");

#5

This probably isn’t an ideal solution, but it passed. It uses a for loop and doesn’t include the replace Method.

function titleCase(str) {
  str = str.split(' ');

  for (i = 0; i < str.length; i++) {
    str[i] = str[i].toLowerCase().split('');
    str[i][0] = str[i][0].toUpperCase();
    str[i] = str[i].join('');
  }

  return str.join(' ');
}

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

#6

When I am testing my code it works fine, but when I put it into FCC code area and run it returned right answer but wouldn’t submit the task.

    function titleCase(str) {
    var newString = "";
    var lowerStrArr = str.toLowerCase().split(" ");
    for (var i = 0; i < lowerStrArr.length; i++) {
        eachWord = lowerStrArr[i].charAt(0).toUpperCase()+lowerStrArr[i].substr(1);
        newString = newString + " " + eachWord;
    }
    console.log(newString);
    return newString;

}
titleCase("sHoRt AnD sToUt");

#7

Here is my code


function titleCase(str) {
  var newArray = str.toLowerCase().split(' ');
  var result = [];
  for(var i=0; i < newArray.length ; i++){
    var val = newArray[i];
    result.push(val.replace(val[0], val[0].toUpperCase())) ;    
  }
  return result.join(" ");
}

titleCase("My little tea pot");



#9

function titleCase(str) {
str=str.toLowerCase();
var x = str.split(" “);
var a;
var b;
var c =”";
for(i=0;i<x.length;i++)
{
if(i>0)
c+=" ";

  a=x[i].split("");
  
  b=a[0].toUpperCase();
  
  a.shift();
  a.unshift(b);
  
  c += a.join("");
  
}

return c;
}


#10

My basic solution

function titleCase(str) {
var arrayStr = str.toLowerCase().split(" “);
for(var i = 0; i < arrayStr.length; i++) {
arrayStr[i] = arrayStr[i].replace(/[a-z]/, arrayStr[i].substring(0,1).toUpperCase());
}
return arrayStr.join(” ");
}
console.log(titleCase(“I’m a little tea pot”));


#11

It’s nothing like the solutions I see here, and pretty inelegant, but it works.

function titleCase(str) {

var strArray;

strArray = str.toLowerCase().split(’’);
strArray[0] = strArray[0].toUpperCase();

var i=0;

while (i < strArray.length) {
if (strArray[i] === " " && strArray[i+1] !== " ") {
strArray[i+1] = strArray[i+1].toUpperCase();
}
i++;
}

return strArray.join(’’);
}


#12

I came to same code and it return me all upper case.


#13

I really need to dig deeper into regexp. Super useful for this!
My solution isn’t really new, but just split the str into an array and replaced the first letter of each arr[i] with the upper case version:

function titleCase(str) {
  var sentenceUp = [];
  var words = str.toLowerCase().split(" ");
   for (var i = 0; i < words.length; i++) {
     sentenceUp.push(words[i].replace(words[i][0], words[i][0].toUpperCase()));
   } 
  return sentenceUp.join(" ");
}

titleCase("Effective Altruism is an philosophy and global movement dedicated to...");

#14

This is my solution :smile:

   function titleCase(str) {
      var words = str.toLowerCase().split(' ');
      for(var i = 0; i<words.length;i++) //   for(var i in words)
        words[i] = firstLetterUp(words[i]);
      str = words.join(' '); 
      return str;
    }

function firstLetterUp(str) {
  var word = str.split('');
  word[0] = word[0].toUpperCase();
  str = word.join('');
  return str;
}

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

#15

Really? What’s it do if you copy and paste mine (as a test)?


#16

function titleCase(str) {
var frase = str.split(’ ');
var texto = “”;
for(var i=0;i<frase.length;i++){
texto = texto + " " + frase[i].charAt(0).toUpperCase() + frase[i].substr(1).toLowerCase();
}
return texto.trim();
}

titleCase(“I’m a little tea pot”);


#17

Silly String: Lazy

function titleCase(str) {
var words = str.split(" ");
var letters = [];

for (var i = 0; i < words.length; i++) {
letters.push(words[i].toUpperCase().slice(0, 1) + words[i].toLowerCase().slice(1));
}

var title = letters.join(" ");

if (str.slice(0, 1) !== letters.slice(0, 1)) {
return title;
}

}

titleCase(“HERE IS MY HANDLE HERE IS MY SPOUT”);


#18
function titleCase(str) {
  var array = str.split(" ");

  for(var x =0;x< array.length;x++){
    var wordMinusFirst ="";
  
    for(var i = 1; i<array[x].length;i++){
      wordMinusFirst = wordMinusFirst.concat(array[x][i].toLowerCase());
    }
    array[x] = array[x][0].toUpperCase() + wordMinusFirst;
  }
  
  str= array.join(" ");
  
  return str;
}

#19

I did not use the replace method, but just .toLowerCase all of the char. well here is the solution i came up with.

    function titleCase(str) {
    var nString=[];
    var nArry=[];

   nString=str.toLowerCase().split(' ');

   for(var i=0;i<nString.length; i++){
   nArry.push(nString[i][0].toUpperCase()+nString[i].slice(1));
   }

  nString=nArry.join(' ');
  return nString;
  }
  titleCase("I'm a little tea pot");

#20
function titleCase(str) {
  var strArray = str.toLowerCase().split(" ");
  for (var i=0; i<strArray.length; i+=1) {
    strArray[i] = strArray[i].charAt(0).toUpperCase() + strArray[i].substring(1);
  }  
  return strArray.join(" "); 
}
titleCase("sHoRt AnD sToUt");

Worked for me - seems quite short and sweet.

Start off with converting the string to lower case and then splitting it into an array

var strArray = str.toLowerCase().split(" ");

Then use a standard for loop to iterate through the array

for (var i=0; i<strArray.length; i+=1) {}

Then change each value in the array

strArray[i] =

Converts the first letter in the string to uppercase

strArray[i].charAt(0).toUpperCase()

then concatenate on the end of the string, omitting the first letter

+ strArray[i].substring(1)

then join it all back up into one string and return it

return strArray.join("");

Edit - just saw @rodrigodiego did something similar above, just converted to lower case in during the for loop… nice!


#21

Hey, this is my solution :slight_smile: It 's a bit complicated however seems to work, but don’t know why fCC won’t agree with me…

function titleCase(str) {

var arr = str.split(’ '),
lowerCase,
upperCase,
container,
finishString ="";

for(var i =0; i<arr.length; i++){
lowerCase = arr[i].toLowerCase();
container = lowerCase.split("");
upperCase = container[0].toUpperCase();
container.shift();
container.unshift(upperCase);
finishString = finishString + container.join(’’) + " ";
}
return finishString;
}

titleCase(“I’m a little tea pot”);