2

I am kinda new to js and would appreciate some help to clarify one subject. Basically i want to call some functions that i write like default javascript are called:

//declaring function
const splitAsExample = text => text.split('|')

//calling function
splitAsExample('Yesterday|Today|Tomorrow')

Instead of calling the function as mentioned above, i would like to know if it's possible to make a function that can be called like:

'Yesterday|Today|Tomorrow'.splitAsExample()

//and || or
'Yesterday|Today|Tomorrow'.splitAsExample

I learned js all by myself and didn't manage to find a specific name for this question to search up in google. :) If you can clarify this topic for me it would be great, but if you could give me the name to search it up would be even better!

Andreas
  • 21,535
  • 7
  • 47
  • 56
Farah
  • 43
  • 5
  • Add it to the prototype of String ```String.prototype.splitAsExample``` – Harmandeep Singh Kalsi Aug 31 '20 at 10:56
  • 1
    `'Yesterday|Today|Tomorrow'.splitAsExample()` would be possible but you would have to mess with the prototype of the builtin `String` object: [How does JavaScript .prototype work?](https://stackoverflow.com/questions/572897/how-does-javascript-prototype-work) – Andreas Aug 31 '20 at 10:57

1 Answers1

2

You could add a prototype function to String.

This allows method chaining with a given object.

String.prototype.splitAsExample = function () { return this.split('|'); };

console.log('Yesterday|Today|Tomorrow'.splitAsExample());
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • _"You could..."_ - But there's almost always a better way instead of modifying the prototype of a builtin object like `String` – Andreas Aug 31 '20 at 10:58