Basic Alogrithm Scripting Challenges [TitleCase]

Hi guys, could someone please explain how this code is working?

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 happening when something is passed to replaceAt? What exactly is passed to it, and what does replaceAt do with it? Specifically this line: this.substr(0, index) + character + this.substr(index+character.length). I don’t get heads or tails of what that line is doing, what it’s adding, and what the end product is that it’s returning.

The code extends builtin String by adding replaceAt to its prototype - then replaceAt can be used in a chain of function calls

The this reference in replaceAt is to the string object on which the function is called - the function extracts two pieces of the string - the initial part up to just before index and the trailing part from index+character.length onward - it pastes the two pieces together with character in between and returns the new string

Effectively replaceAt replaces a portion of a string starting at a given index with another string

1 Like