1

I am trying to write a function which returns the middle character of a string. I want it to work like the code below :

"123456789".midChar(); // Returns 5
"hello".midChar(); // returns 1
"test".midChar(); // returns e

I want to know how can I access the string if the function takes no parameters? How can I refer to the strings inside of the function to be able to manipulate it? For example "123456789"

What have I done before asking this question?

I read about prototypes and understood how I can add methods to the array and string prototype. I tried to find the implementation of String.prototype.charAt() and several other ones to understand how it's built, but couldn't find one. All i was able to find is Reduce, ForEach and several other Array methods, but that wasn't very helpful to my case.

3
  • Inside the prototype, the string will be set as the context, so you can access it via this. Commented Oct 19, 2018 at 14:59
  • Why does it have to be a method on String rather than a plain function that takes a string as an argument? Commented Oct 19, 2018 at 15:01
  • Just for educational purposes, i want to know how prototypes work in depth, so im trying to build this. Commented Oct 19, 2018 at 15:02

3 Answers 3

2

use this inside midChar function to access the string.

String.prototype.midChar = function() {
  var mid = parseInt((this.length - 1) / 2)
  return this.substring(mid, mid+1);
}

console.log("123456789".midChar())
console.log("hello".midChar())
console.log("test".midChar())

Sign up to request clarification or add additional context in comments.

1 Comment

Is there a reason why you are returning "this.substring(mid, mid+1)" instead of doing "return this[mid];" ?
1

String.prototype.midChar= function () {
    console.log(String(this)); // 'this' is the string representation.
    console.log(this.substring(5));
    console.log(this);
};

"EleFromStack".midChar();
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

0

extend the prototype like this

String.prototype.midChar= function () {
    //put yout function body here..
    //i.e.
    //var firstchar = this.charAt(0)
};

that should do it!

1 Comment

Yes, that wasnt my question. My question is how i can access the string inside of this function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.