Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add method to string class

Tags:

javascript

I'd like to be able to say something like this in javascript :

   "a".distance("b") 

How can I add my own distance function to the string class?

like image 406
will Avatar asked Dec 05 '11 21:12

will


People also ask

How do you add a method to a string class in C++?

add(str1,str2); it should append str1 at the beginning of the string and str2 at the end of the string. This class(inherited string class) is a private member class of another class(say Parent).

How do you add a function to a string?

A better way to create a function from a string is by using Function : var fn = Function("alert('hello there')"); fn(); This has as advantage / disadvantage that variables in the current scope (if not global) do not apply to the newly constructed function.

How to add new method to string in JavaScript?

distance = function (char) { var index = this. indexOf(char); if (index === -1) { alert(char + " does not appear in " + this); } else { alert(char + " is " + (this. length - index) + " characters from the end of the string!"); } };

How to add method to class JavaScript?

Class methods are created with the same syntax as object methods. Use the keyword class to create a class. Always add a constructor() method. Then add any number of methods.


2 Answers

You can extend the String prototype;

String.prototype.distance = function (char) {     var index = this.indexOf(char);      if (index === -1) {         alert(char + " does not appear in " + this);     } else {         alert(char + " is " + (this.length - index) + " characters from the end of the string!");     } }; 

... and use it like this;

"Hello".distance("H"); 

See a JSFiddle here.

like image 126
Matt Avatar answered Sep 22 '22 08:09

Matt


String.prototype.distance = function( arg ) {     // code }; 
like image 26
Will Avatar answered Sep 18 '22 08:09

Will