Search code examples
javascriptobjectprototype

How to create a custom function similar to string.split() to reverse a string


I'm trying to write a function on which if we pass the string like we do for split, it returns a string which is reversed -

This is what I've tried -

var abc = "hello"
var result;
String.prototype.reverser = function(str){
  var temparr = str.split('').reverse().join('');
  return temparr;
}
result = abc.reverser();
console.log(result);

I'm expecting olleh but rather getting -

VM1179:4 Uncaught TypeError: Cannot read property 'split' of undefined at String.reverser (:4:19) at :7:14


Solution

  • You don't need a parameter str. The string is already binded to the method on prototype. Just use this to access the string.

    var abc = "hello"
    var result;
    String.prototype.reverser = function(){
      return this.split('').reverse().join('');
    }
    result = abc.reverser();
    console.log(result);

    Note: You shouldn't directly add enumerable properties to prototype. Instead use Object.defineProperty()

    var abc = "hello";
    Object.defineProperty(String.prototype,'reverser',{
      value:function(){
        return this.split('').reverse().join('');
      }
    })
    var result = abc.reverser();
    console.log(result)