How does this replaceAt function work?

Viewed 11694

Could you please explain how this piece of code works?

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

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

Specifically, what exactly is passed onto to replaceAt (I get that it's passed an index, and a character that's converted to lowercase), but what does replaceAt DO with it?

So, in the first iteration of the loop, it's passed replaceAt(0, i) right? Then what does replaceAt do with this? I just don't get this line:

this.substr(0, index) + character + this.substr(index+character.length)

I've already read this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr. I'm here because I don't understand that return statement and what exactly it's doing.

4 Answers
Related