JavaScript String Extension Methods

It happens sometimes when writing code and cope with an object that you need a functionality namely a method which the object doesn't expose. And as you do not have ownership over that object as it is provided by the language or framework, it appears the need somehow to extend that object to have the desired behavior. In that case JavaScript is a language which is powerful and flexible enough to easily solve the problem. It provides a way to generate extension methods fast.

Let us look at the JavaScript String object. As developers who have experience in .NET and Java know the string class defines a rich variety of helper methods to work with a string. For example there is
the trim() method which we can call on the string object and strip it off any leading and trailing whitespaces. Each object in the JavaScript language has a prototype property which can be used for that purpose. It gives the possibility to extend the object. We can use the String.prototype property and write a method which implements the trim functionality:

<script type="text/javascript">
    if (typeof String.prototype.trim !== "function") {
	    String.prototype.trim = function () {
 		  return this.replace(/^\s+|\s+$/g, "");
 	    };
    }
	
 	var target = "  Trim Test  ";
	console.log(target.trim());
</script>

As seen from code, it is quite easy writing extension methods in JavaScript. We can add some more extension methods to the String object. Suppose we want to have a method to check if string is empty and a method to convert the string into upper cases. Here we even do not have the need to write own implementation as the string has a built-in toUpperCase method. For abbreviation we can name it upper().

<script type="text/javascript">
    if (typeof String.prototype.empty !== "function") {
	    String.prototype.empty = function () {
		   return this.length === 0;
	    };
    }

    if (typeof String.prototype.upper !== "function") {
	    String.prototype.upper = function () {
		  return this.toUpperCase();
	    };
    }
	
	var target = "  Trim Test  ";
	if (!target.empty()) {
		console.log(target.upper());
	}
</script>