How to add method to String class in JavaScript ?
Last Updated :
18 Jul, 2023
In this article, the task is to add a method to the String class in JavaScript. There are two approaches that are described with the proper examples:
Approaches to add Methods to String Class:
The Object.defineProperty() method is used to define a new property directly to an object or modify an existing property. It takes 3 arguments, the first is Object, the Second is propertyName, and the last is propertyDescription. In this example, the sum of the length of strings is returned.
Syntax:
Object.defineProperties(obj, props)
Example: This example uses the above-explained approach.
Javascript
let str1 = "GeeksforGeeks" ;
let str2 = "A Computer Science Portal" ;
console.log(str1);
console.log(str2);
Object.defineProperty(String.prototype, "SumOfLength" , {
value: function (param) {
return this .length + param.length;
},
});
function GFG_Fun() {
let res = str1.SumOfLength(str2);
console.log( "Total length: " + res);
}
GFG_Fun();
|
Output
GeeksforGeeks
A Computer Science Portal
Total length: 38
The String.prototype.propertyName is used to add a new method to the String class. Define a method that takes arguments passed by the object and performs the desired operation. In this example, the sum of the length of strings is returned.
Syntax:
object.prototype.name = value
Example: This example uses the above-explained approach.
Javascript
let str1 = "JavaScript" ;
let str2 = "A Scripting Language for Web" ;
console.log(str1);
console.log(str2);
String.prototype.SumOfLength = function (arg) {
return this .length + arg.length;
};
function GFG_Fun() {
let res = str1.SumOfLength(str2);
console.log( "Total length: " + res);
}
GFG_Fun();
|
Output
JavaScript
A Scripting Language for Web
Total length: 38
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...