Search code examples
javascriptstringfunctionmethodssubstring

How does this replaceAt function work?


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.


Solution

  • Suppose you execute "thisisatest".replaceAt(3, "h").

    Then...

    1. this.substr(0, index) returns "thi" : ie the first 3 characters of "thisisatest"
    2. character returns "h"
    3. this.substr(index+character.length) returns "isatest" : ie all characters of "thisisatest", starting at position 4

    So, when you combine this, you get "thihisatest"