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