0

Can I do something like this?

var mystring = "http%3A%2F%2Fstackoverflow.com%2F";

var mydecodedstring = mystring.apply(decodeURIComponent);

I know I can do this

var mydecodedstring = decodeURIComponent(mystring);

But I'd like to chain this if possible for syntactic purposes. Just curious if it's possible. My goal is:

mystring.?????
  • If you're looking to create a custom `String.method`, take a look at [String.prototype](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype). There is a good article about Method Chaining and using prototype [here](https://schier.co/blog/2013/11/14/method-chaining-in-javascript.html). – Tyler Roper Apr 13 '17 at 17:03
  • Is adding a String method the only way to do this? There's not an existing method that can accomplish this? – Brenton Klassen Apr 13 '17 at 17:08
  • 1
    Yes, adding a method to the prototype method is the only way to do this (if you don't want to write something like `$(mystring).apply(decodeURIComponent)`), and that is [something you really should not do](http://stackoverflow.com/q/14034180/1048572). – Bergi Apr 13 '17 at 17:11

2 Answers2

0

maybe you want to add a new method to String object?

 String.prototype.apply= function(entry){
     return decodeURIComponent(entry);
    }
    var mystring = "http%3A%2F%2Fstackoverflow.com%2F";

    var mydecodedstring = mystring.apply(decodeURIComponent);
Fanyo SILIADIN
  • 802
  • 5
  • 11
0

Your should see this to see how apply works. You could do something like:

var mystring = "http%3A%2F%2Fstackoverflow.com%2F";

var mydecodedstring = decodeURIComponent.apply(null, mystring);

Clearly, apply will not provide what you are looking for.

You could define your own function on the String prototype for decoding or define it only on your object.

user886
  • 1,149
  • 16
  • 16