Trimming a string in javascript
Introduction
For those of you who develop applications using the .NET Framework are no doubt familiar with the many tools that are available to work with and manipulate strings. I have found that many of those methods are also built into javascript. Unfortunately, some of my favorite methods I use often, the trim methods, are not available.
I decided I should create my own functions to mimic the same behavior in javascript. The actual trimming of the string is fairly simple using regular expressions. So I started out by creating a function that accepts a string as an argument and then returns a new string with the whitespace removed. Simple enough but it just didn’t sit right with me as it didn't completely mimic the String class in the .NET Framework.
I created a list of a few requirements I wanted to meet before I was completely satisfied.
- I must be able to call the trim function on any string the same way I do in the CLR
- I should be able to trim the start, end or both
Thankfully, it is possible to meet these requirements. Every class in javascript has a prototype object which allows you to extend that class. So with that let’s start writing some code. The trim function will basically perform the task of trimming the start and end. So we should build the trimStart function and trimEnd function first.
String.prototype.trimStart = function()
{
return this.replace(/^\s*/, '');
}
String.prototype.trimEnd = function()
{
return this.replace(/\s*$/, '');
}
String.prototype.trim = function()
{
return this.trimStart().trimEnd();
}
That’s it! Simple enough. And once I put these functions into an external js file and add a link to it in a web page I can trim any string just by calling it’s trim() function. Enjoy!