Jump to: navigation or main content.

The trim function

The function makes 3 regular expression calls to remove spaces at the start, the end and any multiple spaces.

// remove multiple, leading or trailing spaces 
function trim(s) {
s = s.replace(/(^\s*)|(\s*$)/gi,"");
s = s.replace(/[ ]{2,}/gi," ");
s = s.replace(/\n /,"\n"); return s;
}

To use it, do something like this:-

alert(trim(" My name is stewart "));

It will strip the spaces at the start, end and also any multiple spaces in the middle to give a nicely formatted string! Simple, eh?


Comments (8)

What others have said about this blog post.

  1. 11 May 2007 Ace_NoOne said:

    Very nice - thanks! (Why the s.replace(/\n /,"\n") though - what's that for?)

  2. 16 May 2007 Stewart said:

    That simply removes any spaces that come after a new line. It could be optimized to remove multiple spaces after a new line.

  3. 01 May 2008 Rishi Katara said:

    working very nice, thanx.

  4. 25 Jul 2008 Ryan said:

    Implement the trim method as a prototype. Have a look at this article: http://www.whadiz.com/what-is.aspx/programming/javascript/javascript-trim

  5. 02 Jun 2010 Hector said:

    Thanks, I was trying hard to make it work, found regexp to be kinda confusing, your method is great.

  6. 12 Sep 2011 SanthanaKrishnan N said:

    Can u pls explain me the code.. am a newbie to javascript..

  7. 09 Nov 2011 Mads said:

    Thanks a lot for the code. It is very helpful for people like me:)

  8. 30 Aug 2012 Sascha said:

    Great Stuff !!!!!!!


This thread has been closed from taking new comments.