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!

Suprodeep    4/8/2008 6:28 AM

Hi Rob,

 

Lets say my email is suprodeep@gmail.com. And i always want to trim it down to the first half of the email address. ie any name followed by @ needs to replaced by just the name and the rest followed should be discarded.

 

Can it be done using this javascript...

.NET Advisor    4/8/2008 4:48 PM

Hi Suprodeep,

 

You certainly can use regular expressions to pull a certain string out of another string. This particular example is only about replacing the leading and trailing whitespace though.

 

If you wanted to pull the name from an email in javascript you could do it like this:

 

Let's say you have a variable named "email" whose value you retrieved from an input. This line of javascript would return the name from it:

 

email.substring(0, email.indexof('@'));

suprodeep    4/21/2008 4:01 AM

Thanks a lot for the valuable piece of information...

New Comment

  
  
  
  
Download Source Code
Email Print