freeCodeCamp Challenge Guide: Title Case a Sentence

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 chould start by splitting the string into an array of words.

Hint 2

  • You should make the word lowercase and make the first letter uppercase.

Hint 3

  • You will need to create a new string with pieces of the updated words.

Solutions

Solution 1 (Click to Show/Hide)
function titleCase(str) {
  const newTitle = str.split(" ");
  const updatedTitle = [];
  for (let st in newTitle) {
    updatedTitle[st] = newTitle[st][0].toUpperCase() + newTitle[st].slice(1).toLowerCase();
  }
  return updatedTitle.join(" ");
}

Code Explanation

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) {
  return str
    .toLowerCase()
    .split(" ")
    .map(val => val.replace(val.charAt(0), val.charAt(0).toUpperCase()))
    .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 3 (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

168 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");
54 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");
127 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");
6 Likes

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


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

3 Likes

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

2 Likes

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

6 Likes

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...");
9 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");
12 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”);

2 Likes
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;
}
3 Likes

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

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