How does this replaceAt function work?

前端 未结 4 1660
栀梦
栀梦 2021-01-13 15:18

Could you please explain how this piece of code works?

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


        
相关标签:
4条回答
  • 2021-01-13 15:43

    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)).

    0 讨论(0)
  • 2021-01-13 15:45

    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;

    0 讨论(0)
  • 2021-01-13 15:46

    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"

    0 讨论(0)
  • 2021-01-13 16:00

    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
    
    0 讨论(0)
提交回复
热议问题