String Trimming via the String Object Prototype

Downloadable Files

string_trimming_prototype.htm ( 3,009 Bytes )

Prototyping can be used to give built in Javascript objects global methods. In this case, we are using Prototype to give the String object the methods trim(), leftTrim(), and rightTrim(). You would call these on the String object the same way you would call indexOf() or toLowerCase(), as if it were part of the natural String object.

  • // Give string object the trim method.
  • String.prototype.trim = function(){
  • return( this.replace(new RegExp("^([\\s]+)|([\\s]+)$", "gm"), "") );
  • }
  •  
  • // Give string object the left trim method.
  • String.prototype.leftTrim = function(){
  • return( this.replace(new RegExp("^[\\s]+", "gm"), "") );
  • }
  •  
  • // Give string object the right trim method.
  • String.prototype.rightTrim = function(){
  • return( this.replace(new RegExp("[\\s]+$", "gm"), "") );
  • }

Added May 3, 2006 / Updated May 3, 2006