Could you please explain how this piece of code works?
String.prototype.replaceAt = function(index, character) {
return this.substr(0, index) + characte
this.substr
is a function that operates on a string and returns a 'sub string' of the string. See a tutorial here: https://www.w3schools.com/jsref/jsref_substr.asp
So what replaceAt
is doing is operating on a string and replacing the character at the target index, index
, with the new substring, character
. Indeed the passed character
does not have to be only one character but could be multiple, like abcd
. It is rather poorly named.
For more detail, using substr()
, it is taking the first part of the string from index 0
to index
, adding the 'character/string' passed to the function, and then taking the rest of the string from index index+character.length
onwards. Note that substr
has an optional parameter which is used in the first call (this.substr(0,index)
).
The replaceAt function simply takes the index of a character (0 in this case) and replaces it with another character (in this case the uppercase version of the original character. This specific function is just Title Casing a word by replacing the first character with the same character in uppercase.
The line that your questioning, takes a substring of the word before the character at the specificied index this.substr(0,index)
since substr is non-inclusive of the last index, appends the specified character + character
, and appends a substr of the rest of the word + this.substr(index+character.length)
Example 'testing'.replaceAt(0,testing
.charAt(0).toUpperCase());
= '' + 'T' + 'esting' = Testing;
Suppose you execute "thisisatest".replaceAt(3, "h")
.
Then...
this.substr(0, index)
returns "thi"
: ie the first 3 characters of "thisisatest"
character
returns "h"
this.substr(index+character.length)
returns "isatest"
: ie all characters of "thisisatest"
, starting at position 4So, when you combine this, you get "thihisatest"
Lets imagine this easy case:
"0123456789". replaceAt(2/*index*/,"000"/*character*/)
Then this happens:
this.substr(0, index/*2*/)//"01"
+ character //"000"
+ this.substr(index/*2*/+character.length/*3*/)//"56789"
Output:
0100056789