Title Case a Sentence - I have a question!

Tell us what’s happening:

I have completed this challenge. However, when referring to some other ways, I see the code below and have some questions about it.

  1. . Why have this part at the beginning
String.prototype.replaceAt = function(index, character) {
    return this.substr(0, index) + character + this.substr(index+character.length);
};
  1. What is replaceAt (), I search the web and have not seen anything about it and if it is a function, what does it do in the code below?

  2. The code below is quite confusing, can someone explain an easy way to help me? Thanks very much.

Your code so far


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

1, 2. replaceAt is not part of the JavaScript standard. This is a custom function that someone wrote to add to the String method of JavaScript. (Obviously not standardized and probably did it to use as a helper function). Since it’s part of String.prototype you can now call that method on your strings in your program like. "hello".replaceAt or "string".replaceAt()

  1. Basically turning input string into an array -> creating a new array for future storage -> going over each word in the sentence and update each word with replaced letter -> finally return the array that has been joined which is now a string.
1 Like

Thank you, but i have an example as below

String.prototype.replaceAt = function(index, character) {
    return this.substr(0, index) + character + this.substr(index+character.length);
};

'testing'.replaceAt(0,testing.charAt(0).toUpperCase()); = '' + 'T' + 'esting' = Testing;

I can understand why (0, index) =’ ’
but I still don’t understand why character = ‘T’ and (index + character.length) = ‘esting’.
can you explain it to me, thanks.

'testing'.replaceAt(0,testing.charAt(0).toUpperCase());

In the example code you posted above, this will error out, because testing is not a defined. Did you mean to post the following instead?

'testing'.replaceAt(0,'testing'.charAt(0).toUpperCase());

If so, the reason is because 'testing'.charAt(0).toUpperCase() is passed as the 2nd argument to the replaceAt method. Inside the method, this value is represented by the character parameter, which is where the “T” comes from.

Why? Because 'testing'.charAt(0).toUpperCase() is “T”.

1 Like

Thanks, but if ‘testing’.charAt (0) .toUpperCase () is “T”. so why this.substr (index + character.length) is equal to ‘esting’?

Because index is 0 and character.length is 1. 0 + 1 = 1, so it starts at the 2nd character of testing, which is e.

1 Like

i got it, thank you very much!!!