How to Trim() a String

Sometimes we all wonder: how is it that such a widespread language as javascript does not already have a built-in function like trim()?!
Weird, yes. Easy, yes, too. In fact, you can simply extend the String object with any number of methods that you can that apply, as long as your script file is included, much like extension methods in C#. All you’d have to do is regular expressions and here are three functions for left, right and both trimming of a string:

String.prototype.trim = function() 
	return this.replace(/^\s+|\s+$/g,"");
String.prototype.ltrim = function() 
	return this.replace(/^\s+/,"");
String.prototype.rtrim = function() 
	return this.replace(/\s+$/,"");

Now, if you don’t get it quite, the path leads to regular expressions and OOP.
I have, however, found it quite a helpful thing to have around, one that one might even put into a base library as a resource, if you’re using .NET.

This entry was posted in Javascript and tagged , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *