Isn’t this.substr(0, index) always this.substr(0, 0)? Why is it necessary? I attempted to use Javascript Tutor to see what’s happening in the user-defined replaceAt function, but I can’t see why this.substr(0,0) is needed because JT doesn’t show exactly what’s happening. The code is quickly run and spits out the result.
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(" ");
}
In this case, yes. But, the function is made in such a way that you could choose to replace at a different index, and are not limited to always replacing the first.
Ah. Well, first thing to recognise is what is being passed to the replaceAt function:
In this case:
.replaceAt(0, newTitle[st].charAt(0).toUpperCase())
//Same as
.replaceAt(0, 'I')
Now, what does the substr method do: https://www.w3schools.com/jsref/jsref_substr.asp
In this case, the this keyword is referencing the object the replaceAt function was called on:
the lowerCase value of newTitle[st] == "I"
Now, substr(0,0) returns nothing. Same with substr(1) on an object of length 1.