How to add method to String class in JavaScript ?
In this article, the task is to add a method to the String class in JavaScript. Two approaches are described with the proper examples:
Approaches to add Methods to String Class:
Table of Content
Approach 1: Using Object.defineProperty() method
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.
// Input string
let str1 = "GeeksforGeeks";
let str2 = "A Computer Science Portal";
// Display input string
console.log(str1);
console.log(str2);
// Define custom method
Object.defineProperty(String.prototype, "SumOfLength", {
value: function (param) {
return this.length + param.length;
},
});
// Run custom method
function GFG_Fun() {
// Apply custom method
let res = str1.SumOfLength(str2);
// Display output
console.log("Total length: " + res);
}
// Funcion call
GFG_Fun();
Output
GeeksforGeeks A Computer Science Portal Total length: 38
Approach 2: Using String.prototype.propertyName method
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.
// Input string
let str1 = "JavaScript";
let str2 = "A Scripting Language for Web";
// Display input string
console.log(str1);
console.log(str2);
// Define custom method
String.prototype.SumOfLength = function (arg) {
return this.length + arg.length;
};
// Run custom method
function GFG_Fun() {
// Apply custom method
let res = str1.SumOfLength(str2);
// Display output
console.log("Total length: " + res);
}
// Funcion call
GFG_Fun();
Output
JavaScript A Scripting Language for Web Total length: 38
Approach 3: Using ES6 Classes
With ES6, you can use class syntax to define methods that will be added to the prototype of the String class. This approach allows for more structured and modern code.
Example:
// Input string
let str1 = "Open";
let str2 = "AI";
// Display input string
console.log(str1);
console.log(str2);
// Define custom method using ES6 class
class CustomStringMethods {
constructor(str) {
this.str = str;
}
// Custom method to calculate sum of lengths
sumOfLength(otherStr) {
return this.str.length + otherStr.length;
}
}
// Add custom method to String prototype
String.prototype.CustomStringMethods = function () {
return new CustomStringMethods(this);
};
// Run custom method
function customMethodExample() {
// Apply custom method
const customString1 = str1.CustomStringMethods();
const customString2 = str2.CustomStringMethods();
const res = customString1.sumOfLength(str2);
// Display output
console.log("Total length: " + res);
}
// Function call
customMethodExample();
Output
Open AI Total length: 6
Approach 4: Using ES6 Symbols
Symbols are a new primitive type introduced in ES6, and they are often used to add unique properties to objects, ensuring that property names do not collide with other properties. This approach leverages Symbols to add a method to the String class.
Example: This example demonstrates how to use Symbols to add a method to the String class to calculate the sum of the lengths of two strings.
// Input string
let str1 = "Hello";
let str2 = "World!";
// Display input string
console.log(str1);
console.log(str2);
// Define a unique Symbol
const sumOfLengthSymbol = Symbol('sumOfLength');
// Define custom method using Symbol
String.prototype[sumOfLengthSymbol] = function(arg) {
return this.length + arg.length;
};
// Run custom method
function customMethodWithSymbolExample() {
// Apply custom method
let res = str1[sumOfLengthSymbol](str2);
// Display output
console.log("Total length: " + res);
}
// Function call
customMethodWithSymbolExample();
Output
Hello World! Total length: 11
Approach 5: Using Object.assign
Using Object.assign to add a method to the String prototype involves extending the String class by assigning a new method directly to String.prototype. This allows the method to be available on all string instances.
Example
Object.assign(String.prototype, {
reverse() {
return this.split('').reverse().join('');
}
});
console.log("hello".reverse()); // "olleh"
Output
olleh