1

I'm trying to title case a string which capitalizes only the first character in each word. I tried doing it using the following code. This is what I've done till now.

function titleCase(str) {
 var lowstr = str.toUpperCase();
  var array=lowstr.split(' ');
  var arr;
  var arr1;
   for(var i=0;i<array.length;i++)
    {
      arr1=array[i].substring(0,1); 
      
      for(var j=0;j<array[i].length;j++)
        {
      arr=array[j].substring(1).toLowerCase();
        }
      arr=arr1.concat(arr);     
    }
        array.join(" ");
  return array;
}

titleCase("I'm a little tea pot");
  • 1
    It's great that you've got that, but what is your problem? – byxor Aug 18 '16 at 11:41
  • The code isn't working. I can't seem to rectify the error. The error's showing up as "array[j] is undefined". I thought the variable j will act as the index. – flatbreadcandycane Aug 18 '16 at 11:44
  • 1
    Possible duplicate http://stackoverflow.com/questions/1026069/how-do-i-make-the-first-letter-of-a-string-uppercase-in-javascript – roberrrt-s Aug 18 '16 at 11:50

5 Answers5

2

It appears as if you're trying to do too much in your titleCase function. I would take a slightly different approach that follows Single Responsibility Principle a little more closely.

I would have...

  1. A function to titleCase a single word.
  2. A function that titleCases each word in a sentence.

Example:

function titleCaseSingleWord(word) {

    if (word.length === 0) {
        return "";
    }

    var result = word[0].toUpperCase();
    for (var i = 1; i < word.length; i++) {
        result += word[i].toLowerCase();
    }

    return result;
}

function titleCaseSentence(sentence) {
    var titleCasedWords = [];

    var words = sentence.split(" ");
    for (var i = 0; i < words.length; i++) {
        var word = words[i];
        var titleCasedWord = titleCaseSingleWord(word);
        titleCasedWords.push(titleCasedWord);
    }

    return titleCasedWords.join(" ");
}

console.log(titleCaseSentence("im a liTTLE teapot"));
// "Im A Little Teapot"

Reasoning Behind Multiple Functions:

  • It makes it easier to test each individual function and find the errors quicker. It also helps to keep your functions shallow.

Notes:

  • These functions are a little bit messy and could do with some refactoring, but I'll leave that to you as a mini exercise.

  • Also, one could go further and say that titleCaseSentence is both splitting the words and titleCasing them, so it should be split up further. That's entirely up to you whether you want to do that or not.

byxor
  • 5,930
  • 4
  • 27
  • 44
1

Regular expressions solution to the problem:

console.log(
//Base string
"i'm a little tea pot"
//Enforce lowercase
  .toLowerCase()
  //Regular expression replace with uppercase
  .replace(
    /(\s+.)|^\w/ig,
    function(v) {
      return v.toUpperCase();
    })
);
Emil S. Jørgensen
  • 6,216
  • 1
  • 15
  • 28
  • This is NICE! I was toying with this implementation and wondering how to capitalize the match of a regex. Wasn't aware a callback could be used with replace. Awesome! – PakiPat Jun 23 '17 at 22:09
0

you set them all to uppercase, then find the letters that are supposed to be lower case.

What I'd do is the opposite. I'd start off the same, with

arr = str.split(" ")

but then you can go

for(var x = 0; x < arr.length; x++)

arr[x].substring(0,1) = arr[x].substring(0,1).toUpperCase()

and then join them back up.

Can't see why you'd need a nested loop for this.

S.V.
  • 1,181
  • 6
  • 23
0

If you're willing to forgo substring and consider a more 'functional' approach, try this.

String.prototype.titleCase = function() {
    t = this.toLower().split(' ').map((word) => word.charAt(0).toUpperCase()+word.slice(1)).join(' ');
    return t;
}

Since I've declared the function on the String.prototype, you can use it thus:

"This is a title".titleCase() // >> "This Is A Title"

which may not be 100% the way newspaper editors would have it, but it does what you seem to want it to do. Let me know if you need an explanation.

Also, if you want a function to use thus: TitleCase("some sentence here") you can easily refactor the code. Let me know if you need further explanation.

PakiPat
  • 1,020
  • 14
  • 27
-1

Check This Out..

function titleCase(str) {

 var arr=str.split('');
 var array=[];

for(var x=0;x<arr.length;x++)
   { if(x==0){
  array[x]=arr[x].toUpperCase();
  x++;
      }

 array[x]=arr[x].toLowerCase();

  if(arr[x]==' ')
    {
      array[x+1]=arr[x+1].toUpperCase();
      x++;
    }
}
var st=array.join('');
return st;
 }

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