4

So, I want to convert a string into a Title Case string. I've written this code but I get the same string in lowercase when I run this. Could anyone please point out where I'm wrong with this? Any help is much appreciated.

function capitalize(str) {
    return str.toUpperCase();
}

function titleCase(str1) {
    str1 = str1.toLowerCase();
    var arr = str1.split(' ');
    var l = arr.length;
    var m;

    for (var i = 0; i < l; i++) {
        m = arr[i].length;
        for (var j = 0; j < m; j++) {
            if (j === 0) {
                arr[i][0] = capitalize(arr[i][0]);
            }
            else {
                arr[i][j] = arr[i][j];
            }
        }
    }
    return arr;
}

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

3 Answers3

5

I'm pretty sure you were given advice on exactly this question earlier, but using ES5 methods (you can downgrade it to for loops yourself).

function titleCase(str1) {
  return str1.toLowerCase().split(' ').map(function(word) {
    return word.charAt(0).toUpperCase() + word.slice(1);
  }).join(' ');
}
document.body.textContent = titleCase("I'm a little tea potty");
<script src="https://cdnjs.cloudflare.com/ajax/libs/es5-shim/4.4.1/es5-shim.min.js"></script>

Now, what's with your code?

function capitalize(str) {
  return str.toUpperCase();
}
function titleCase(str1) {
  str1 = str1.toLowerCase();
  var arr = str1.split(' ');
  var l = arr.length;
  var m;

  for (var i = 0; i < l; i++) {
    m = arr[i].length;
    for (var j = 0; j < m; j++) {
      if (j === 0) {
        arr[i][0] = capitalize(arr[i][0]);
      } else {
        arr[i][j] = arr[i][j];
      }
    }
  }
  return arr;
}
document.body.textContent = titleCase("I'm a little tea potty");

Let's look at it bit by bit:

function capitalize(str) {
  return str.toUpperCase();
}

Nothing wrong with the above, except that it seems pretty pointless to functionalise.

So, now we have your function, you take an argument (a string) and then you make it all lower cased

function titleCase(str1) {
  str1 = str1.toLowerCase();

So here comes your string "I'm a little tea potty" and it becomes "i'm a little tea potty". So far so good. Then you split it at spaces.

  var arr = str1.split(' ');
  var l = arr.length;
  var m;

Along comes your string and becomes var arr = ["i'm","a","little","tea","potty"]; and l becomes 5, the length of this array. Next you intend to loop through the array arr, that looks fine

for (var i = 0; i < l; i++) {

So for each word (a string) in the array (iteration) you get the length of the string, the first i'm is 3.

m = arr[i].length;

Then you intend to iterate each character in the word, which is fine

for (var j = 0; j < m; j++) {

Then, you are saying if it is the first character of the word then I want a capital letter, otherwise do nothing with it.

  if (j === 0) {
    arr[i][0] = capitalize(arr[i][0]);
  } else {
    arr[i][j] = arr[i][j];
  }

But here's the problem, you try to write the characters back to the string, which is immutable. No errors are thrown, just nothing changes, it's like the string has a read-only switch, just like on a memory card. So your loops continue on and on, do nothing, until all is done. Then you return the array.

return arr;

And surpirise, it is just the same as when you split the sentence into words. ["i'm","a","little","tea","potty"]

Xotic750
  • 22,914
  • 8
  • 57
  • 79
  • `map` function was used. :) – asakura89 Dec 26 '15 at 08:21
  • So then how do you change the string? I suppose you could make a new array and copy it into that, but declaring arrays in javascript without a predefined size always throws up "TypeError:Cannot read property '0' of undefined." I was able to create a program using charAt and slice but just wondering if it can be done with some small variations in my code. – Prateek Taneja Dec 27 '15 at 07:29
  • You can't change the string, you create a new one. Of course if you change your code with this in mind, then it should work (as long as you don't add some other bug). – Xotic750 Dec 27 '15 at 07:32
0

I have changed your code. This will help you ..

function capitalize(str) {
    return str.toUpperCase();   
}

function titleCase(str1) {
    str1 = str1.toLowerCase();
    var arr = str1.split(' ');
    var l = arr.length;
    var m;  

    for (var i = 0; i < l; i++) {
        m = arr[i].length;
        arr[i] = capitalize(arr[i][0])+arr[i].substr(1);        
    }   
    return arr; 

}

titleCase("I'm a little tea potty");
Mukesh Singh Thakur
  • 1,335
  • 2
  • 10
  • 23
0

One liner here

function titleCase(str) {
    return str.split(' ').map(function(s){
       return s.slice(0, 1).toUpperCase() + s.slice(1);
    }).join(' ');
}

titleCase("I'm a little tea potty");
user3896501
  • 2,987
  • 1
  • 22
  • 25