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.
- . Why have this part at the beginning
String.prototype.replaceAt = function(index, character) {
return this.substr(0, index) + character + this.substr(index+character.length);
};
-
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?
-
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()
- 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.
Thanks, but if ‘testing’.charAt (0) .toUpperCase () is “T”. so why this.substr (index + character.length) is equal to ‘esting’?
i got it, thank you very much!!!