Snippets v2

Languages
My Snippets

Trim Whitespace from Strings Login or Register to Bookmark this snippet

Description Javascript

This little peice of ingenious code builds on the protype to add trim() functionality to strings, thus trimming whitespace from either the left, right, or both sides of the string.

example of usage:
var sOriginal=' text ';
sTrim = sOriginal.trim();
sLTrim=sOriginal.ltrim();
sRTrim=sOriginal.rtrim();

After execution:
sOriginal is ' text '
sTrim is 'text'
sLTrim is 'text '
sRTrim is ' text'

Found this years ago on the web - can't remember where..

The Code Download
  1. String.prototype.trim=function(){
  2.     return this.replace(/^s*|s*$/g,'');
  3. }
  4. String.prototype.ltrim=function(){
  5.     return this.replace(/^s*/g,'');
  6. }
  7. String.prototype.rtrim=function(){
  8.     return this.replace(/s*$/g,'');
  9. }
Credits Contact JC

Added by JC on 12th November, 2007

Comments

There are no comments about this snippet.

Post Comment HTML is allowed

You must be registered and logged in to post a comment.

Login here to post a comment