Add Custom Method to String Object

Add custom method to string object

You can't because the builtin-types are coded in C. What you can do is subclass the type:

class string(str):
def sayHello(self):
print(self, "is saying 'hello'")

Test:

>>> x = string("test")
>>> x
'test'
>>> x.sayHello()
test is saying 'hello'

You could also overwrite the str-type with class str(str):, but that doesn't mean you can use the literal "test", because it is linking to the builtin str.

>>> x = "hello"
>>> x.sayHello()
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
x.sayHello()
AttributeError: 'str' object has no attribute 'sayHello'
>>> x = str("hello")
>>> x.sayHello()
hello is saying 'hello'

Add method to string class

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.

Javascript adding methods to String instance

Strings and numbers are autoboxed primitives, meaning that when you perform OO operations on them, they are cast as "String" and "Number" classes but then are immediately unboxed.

Your code evaluates to:

x = "123"
(new String(x)).method = function() { console.log("test") }

(new String(x)).method() // Error

Your second call is failing because you are dealing with an entirely different String object. As T.J. stated, you can get around this by making x a String object, but this is not a common or recommended practice.

You can extend all strings by adding the method to String.prototype:

x = "123"
String.prototype.method = function() { console.log("test") }

x.method()

This call evaluates the same way as (new String(x)).method() but since that method exists in the prototype, it will get called.

Convert string to class object and add custom function to it in Python

I think you can follow this template:

class StrToObj:
def __init__(self, name, ...):
self.name = name
...
def do_something_with_file(self, ...):
...

how can i add custom properties to javascript string object

thanks to all of you for your help.but i got the way

Object.defineProperty( String.prototype, 'IsNullOrEmpty', {
get: function () {
return ((0 === this.length) || (!this) || (this === '') || (this === null));
}
});

var str = "";
str.IsNullOrEmpty;//returns true

Javascript custom functions with string

A JavaScript string will inherit functions from its prototype, so you need to add the function to the string prototype. For example:

String.prototype.replicate = function (n) {
var replicatedString = '';

for (var i = 0; i < n; i++) {
replicatedString += this;
}

return replicatedString;
};

See also:

javascript: add method to string class

How to create a String prototype clone and assign custom function to it

A less painful way of achieving this task was to take advantage of the class syntax and all the initialization and binding which one gets for free especially in case one does practice sub-typing of a native class/type like String ...

class MyStr extends String {
upp () {
return this.toString().toUpperCase();
}
}
const newString = new MyStr('this is my own string');

console.log(newString.upp());
console.log(newString+"");

console.log(newString.toString());
console.log(newString.valueOf());
.as-console-wrapper { min-height: 100%!important; top: 0; }

How to use custom created methods of a string prototype?

A couple of issues. The function takes a parameter of str, but you're not calling it with any parameter. The conventional way to reference the instantiated object you're calling a method on is to use this, but you have an arrow function - better to use a standard function so you can use this:

String.prototype.toCapitalize = function() {

let splits = this.split(" ");

let capitalize = '';

splits.forEach((el) => {

let result = el.charAt(0).toUpperCase() + el.substr(1, el.length).toLowerCase();

capitalize = capitalize + ' ' + result;

});

return capitalize;

}

let h = 'its a beautiful weather';

console.log(h.toCapitalize());

Can I add new methods to the String class in Java?

String is a final class which means it cannot be extended to work on your own implementation.



Related Topics



Leave a reply



Submit