0

So, for learning purposes I'd like to recreate the "charAt()" existing method in Javascript which tells you the position of a character in a given string. I'll call the method "CharAtX"

To do so, I've created a function with 2 parameters : The first one is the word, the second is the position, here is the code I have :

function charAtX(word,pos) {
    word_split = word.split("");
    return(word_split[pos])
}

console.log(charAtX("Truck",2))

So, it obviously works, if i call charAtX("truck",2), i will have "u" returned.

But my question is the following :

The original charAt can be called like such

my_word.charAt(3)

Mine can't though. Why is that and how could I change my function into a method so that I can?

Calvin Nunes
  • 6,376
  • 4
  • 20
  • 48
LioM
  • 139
  • 1
  • 2
  • 5

1 Answers1

0

You have to call charAtx function in the context of String object.So, When you call string.charAtx, this object refers to the string. You have to learn prototype and this object in jvascript.

String.prototype.charAtX = function(pos) {
        word_split = this.split("");
        return(word_split[pos])
    }
Chinmoy Samanta
  • 1,376
  • 7
  • 17