freeCodeCamp Challenge Guide: Title Case a Sentence

freeCodeCamp Challenge Guide: Title Case a Sentence
0

Title Case a Sentence


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


Hints

Hint 1

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

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.

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.

Solutions

Solution 1 (Click to Show/Hide)
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(" ");
}

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 its uppercase.

Relevant Links

Solution 2 (Click to Show/Hide)
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");

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

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

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

22 Likes

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");
19 Likes

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");
41 Likes

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");
1 Like

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");


8 Likes

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;
}

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”));

1 Like

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

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

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...");
3 Likes

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");
3 Likes

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

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”);

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”);

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;
}

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");
1 Like
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!

2 Likes

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”);